如何在文本的某一行的末尾附加某些内容

时间:2010-08-24 04:22:44

标签: shell sed awk

我想在某一行的末尾添加一些东西(有一些给定的字符)。 例如,文本是:

Line1:  I just want to make clear of the problem
Line2:  Thanks to all who look into my problem
Line3:  How to solve the problem?
Line4:  Thanks to all.

然后我想在

的末尾添加“请帮帮我”
Line2:  Thanks to all who look into my problem

"Line2"是关键词。 (也就是说,我必须通过关键词grep这一行来附加一些东西)。

所以脚本之后的文字应该是:

Line1:  I just want to make clear of the problem
Line2:  Thanks to all who look into my problem Please help me
Line3:  How to solve the problem?
Line4:  Thanks to all.

我知道sed可以向某些行添加内容但是,如果我使用sed '/Line2/a\Please help me',它会在该行后插入一个新行。那不是我想要的。我希望它附加到当前行。

有人可以帮我吗?

非常感谢!

3 个答案:

答案 0 :(得分:14)

我可能会选择约翰的sed解决方案但是,因为你也问过awk

$ echo 'Line1:  I just want to make clear of the problem
Line2:  Thanks to all who look into my problem
Line3:  How to solve the problem?
Line4:  Thanks to all.' | awk '/^Line2:/{$0=$0" Please help me"}{print}'

输出:

Line1:  I just want to make clear of the problem
Line2:  Thanks to all who look into my problem Please help me
Line3:  How to solve the problem?
Line4:  Thanks to all.

关于它如何工作的解释可能会有所帮助。想想awk脚本,如下左边的条件和右边的命令:

/^Line2:/ {$0=$0" Please help me"}
          {print}

为处理的每一行执行这两个awk子句。

如果该行与正则表达式^Line2:(在行的开头表示“Line2:”)匹配,则通过附加所需的字符串来更改$0$0是整个读入awk)的行。

如果该行符合空条件(所有行都匹配),则执行print。这将输出当前行$0

所以你可以看到它只是一个简单的程序,可以根据需要修改行并输出行,修改或不修改。


此外,即使是/^Line2:/解决方案,您也可能希望使用sed作为密钥,因此您不会在文本中间选择Line2或{{1通过Line20Line29Line200依此类推:

Line299

答案 1 :(得分:7)

sed '/Line2/ s/$/ Please help me/'

答案 2 :(得分:3)

Shell脚本

while read -r line
do 
  case "$line" in
    *Line2* ) line="$line Please help me";;
  esac
  echo "$line"
done <"file" > temp
mv temp file