bash 什么是用于删除行的前 N ​​个字符的 unix 命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/971879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:15:28  来源:igfitidea点击:

What is a unix command for deleting the first N characters of a line?

bashunixcommandtruncate

提问by les2

For example, I might want to:

例如,我可能想要:

tail -f logfile | grep org.springframework | <command to remove first N characters>

I was thinking that trmight have the ability to do this but I'm not sure.

我在想这tr可能有能力做到这一点,但我不确定。

回答by iammichael

Use cut. Eg. to strip the first 4 characters of each line (i.e. start on the 5th char):

使用cut. 例如。去除每行的前 4 个字符(即从第 5 个字符开始):

tail -f logfile | grep org.springframework | cut -c 5-

回答by LB40

sed 's/^.\{5\}//' logfile 

and you replace 5 by the number you want...it should do the trick...

然后你用你想要的数字替换 5 ......它应该可以解决问题......

EDITif for each linesed 's/^.\{5\}//g' logfile

编辑if 对于每一行sed 's/^.\{5\}//g' logfile

回答by Ankur

You can use cut:

您可以使用cut

cut -c N- file.txt > new_file.txt

-c:characters

-c:人物

file.txt:input file

file.txt:输入文件

new_file.txt:output file

new_file.txt:输出文件

N-:Characters from N to end to be cut and output to the new file.

N-:从 N 到 end 的字符被剪切并输出到新文件。

Can also have other args like: 'N' , 'N-M', '-M' meaning nth character, nth to mth character, first to mth character respectively.

也可以有其他参数,如: 'N' 、 'N-M'、 '-M' 分别表示第 n 个字符、第 n 个到第 m 个字符、第一个到第 m 个字符。

This will perform the operation to each line of the input file.

这将对输入文件的每一行执行操作。

回答by les2

tail -f logfile | grep org.springframework | cut -c 900-

would remove the first 900 characters

将删除前 900 个字符

cutuses 900- to show the 900th character to the end of the line

cut使用 900- 显示行尾的第 900 个字符

however when I pipe all of this through grep I don't get anything

但是,当我通过 grep 管道所有这些时,我什么也没得到

回答by John B

I think awkwould be the best tool for this as it can both filter and perform the necessary string manipulation functions on filtered lines:

我认为awk这将是最好的工具,因为它可以过滤并在过滤的行上执行必要的字符串操作功能:

tail -f logfile | awk '/org.springframework/ {print substr(
tail -f logfile | awk '/org.springframework/ && sub(/^.{5}/,"",##代码##)'
, 6)}'

or

或者

##代码##

回答by To Kra

Here is simple function, tested in bash. 1st param of function is string, 2nd param is number of characters to be stripped

这是简单的功能,在 bash 中测试。函数的第一个参数是字符串,第二个参数是要删除的字符数

function stringStripNCharsFromStart { echo ${1:$2:${#1}} }

function stringStripNCharsFromStart { echo ${1:$2:${#1}} }

Usage: enter image description here

用法: 在此处输入图片说明