将所有内容替换为第一个字符串

时间:2014-03-30 17:20:54

标签: regex sed

我尝试对所有内容进行替换,包括第一次出现的字符串但是失败了。

说我有以下字符串:

one two three four five four three two one

我想要

three four five four three two one

但是

sed 's/.*three//'

我最终得到了

two one 

我已尝试使用.*的其他变体 - &gt; <{1}}和(.*$)无济于事。

我已经看过如何替换第一次出现http://techteam.wordpress.com/2010/09/14/how-to-replace-the-first-occurrence-only-of-a-string-match-in-a-file-using-sed/但不是第一次出现的所有内容。

2 个答案:

答案 0 :(得分:1)

由于sed不支持延迟量词?,您可以使用此sed:

echo "$s" | sed 's/.*two \(three\)/\1/'
three four five four three two one

或使用perl:

echo "$s" | perl -pe 's/.*?(three)/\1/'
three four five four three two one

答案 1 :(得分:0)

awk以获得正确的输出

awk '{for (i=1;i<=NF;i++) {if ($i=="three") f=1;if (f) printf "%s ",$i}print ""}' file
three four five four three two one