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

les*_*es2 207 unix bash command truncate

例如,我可能想:

tail -f logfile | grep org.springframework | <command to remove first N characters>
Run Code Online (Sandbox Code Playgroud)

我当时认为tr可能有能力这样做,但我不确定.

iam*_*ael 317

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

tail -f logfile | grep org.springframework | cut -c 5-
Run Code Online (Sandbox Code Playgroud)

  • 问题是,grep在发送它们之前会缓冲大块,因为它可以看到它没有写入终端.使用`grep --line-buffered"org.springframework`来解决这个问题. (6认同)

LB4*_*B40 46

sed 's/^.\{5\}//' logfile 
Run Code Online (Sandbox Code Playgroud)

并且你用你想要的数字替换5 ...它应该成功...

如果每行都编辑 sed 's/^.\{5\}//g' logfile


Ank*_*kur 25

你可以使用cut:

cut -c N- file.txt > new_file.txt
Run Code Online (Sandbox Code Playgroud)

-c: 人物

file.txt: 输入文件

new_file.txt: 输出文件

N-: 从N到最终的字符被剪切并输出到新文件.

还可以有其他参数:'N','N-M',' - M'表示第n个字符,第n个到第m个字符,第一个到第m个字符.

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


Mar*_*ark 10

x=hello

echo ${x:1}
Run Code Online (Sandbox Code Playgroud)

返回你好

根据需要将 1 替换为 N


les*_*es2 8

tail -f logfile | grep org.springframework | cut -c 900-
Run Code Online (Sandbox Code Playgroud)

将删除前 900 个字符

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

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

  • “cut -c 1-900”不会“删除前 900 个字符”——它只会保留前 900 个字符。如果要删除前 900 个字符,请使用“cut -c 901-” (4认同)
  • 'cut -c 900-" 将删除前 899 个字符,不是吗? (2认同)

To *_*Kra 6

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

function stringStripNCharsFromStart {
    echo ${1:$2:${#1}}
}
Run Code Online (Sandbox Code Playgroud)

用法

$ stringStripNCharsFromStart "12abcdefgh-" 2
# 2abcdefgh-
Run Code Online (Sandbox Code Playgroud)

截屏

控制台结果的屏幕截图

  • 您可以将其简化为 echo ${1:$2} (5认同)