从匹配替换为行尾

时间:2011-02-18 22:15:43

标签: regex sed

这应该非常容易,但我无法让它发挥作用。我只想使用 sed 将一个字符串替换为一行的结尾。例如,如果我有以下数据文件:

   one  two  three  five
   four two  five five six
   six  one  two seven four

我希望用“BLAH”这个单词替换单词“two”到最后一行输出:

   one BLAH
   four BLAH
   six one BLAH

不会那样:

   sed -e 's/two,$/BLAH/g'

我不是最好的正则表达式,也许这就是问题

3 个答案:

答案 0 :(得分:50)

这应该做你想要的:

sed 's/two.*/BLAH/'

$ echo "   one  two  three  five
>    four two  five five six
>    six  one  two seven four" | sed 's/two.*/BLAH/'
   one  BLAH
   four BLAH
   six  one  BLAH

$是不必要的,因为.*无论如何都会在行尾完成,而最后的g是不必要的,因为您的第一场比赛将是第一场two 1}}到行尾。

答案 1 :(得分:11)

使用此功能,两个<anything any number of times><end of line>

's/two.*$/BLAH/g'

答案 2 :(得分:3)

AWK

awk '{gsub(/two.*/,"")}1' file

红宝石

ruby -ne 'print $_.gsub(/two.*/,"")' file