【问题标题】:Remove the first word in a text stream删除文本流中的第一个单词
【发布时间】:2011-12-10 11:34:13
【问题描述】:

如何从流中的每一行文本中删除第一个单词?

例如,

$ cat myfile
some text 1
some text 2
some text 3

我想要:

$ cat myfile | magiccommand
text 1
text 2
text 3

我将如何使用 Bash 来解决这个问题?我可以使用awk '{print $2 $3 $4 $5 ....}',但这很麻烦,并且会导致所有空参数都有额外的空格。我在想 sed 可能能够做到这一点,但我找不到任何这样的例子。

【问题讨论】:

标签: bash sed awk cat


【解决方案1】:

运行这个:

sed "s/^some\s//g" myfile

你甚至不需要使用管道。

【讨论】:

    【解决方案2】:

    根据您的示例文本,

    cut -d' ' -f2- yourFile
    

    应该做的工作。

    【讨论】:

    • 警告:我尝试使用它来删除 history 输出上的索引,但由于较小数字之前的空格充当分隔符,它在历史记录开始时不起作用。跨度>
    • @JasonDoucette 不同的输入格式可能需要不同的解决方案
    【解决方案3】:

    要删除第一个单词,直到空格,无论有多少空格,使用:sed 's/[^ ]* *//'

    例子:

    $ cat myfile 
    some text 1
    some  text 2
    some     text 3
    
    $ cat myfile | sed 's/[^ ]* *//'
    text 1
    text 2
    text 3
    

    【讨论】:

      【解决方案4】:

      这是使用awk的解决方案

      awk '{$1= ""; print $0}' yourfile 
      

      【讨论】:

      • 这将在每行的开头留一个空格
      【解决方案5】:

      应该可以的:

      $ cat test.txt
      some text 1
      some text 2
      some text 3
      
      $ sed -e 's/^\w*\ *//' test.txt
      text 1
      text 2
      text 3
      

      【讨论】:

        猜你喜欢
        • 2021-12-11
        • 1970-01-01
        • 2020-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-18
        • 1970-01-01
        相关资源
        最近更新 更多