如何使用sed替换行中的第3个单词

时间:2010-07-18 11:11:04

标签: linux shell sed awk replace

这是我在学习sed过程中的第3篇文章。我有一个假设的要求。我希望能够用'was'替换每行中的第三个单词,其中单词由空格分隔。

bash$ cat words
hi this is me here
hi this   is me again
hi   this   is me yet again
 hi  this   is     me

期望的输出:

hi this was me here
hi this   was me again
hi   this   was me yet again
 hi  this   was     me

人们可以请帮助解决如何使用sed。我尝试了一些执行指令,但没有奏效。 谢谢,

Jagrati

我找到了!我找到了它!

好的,我终于得到了正确的指示。这有效:

sed -e 's/[^ ]*[^ ]/was/3' words

4 个答案:

答案 0 :(得分:7)

如果您不关心格式化,这是一种更简单的方法

$ awk '{$3="was"}1' file
hi this was me here
hi this was me again
hi this was me yet again
hi this was me

答案 1 :(得分:5)

我总是这样做:使用 groups 匹配第一个和第二个单词,然后使用反向引用将它们替换为自己。

sed 's/^\([^ ]*\) \([^ ]*\) is/\1 \2 was/'

答案 2 :(得分:1)

这会查看单词边界而不仅仅是空格,因此当有标点符号时它也能正常工作。它需要GNU sed

$ cat words
hi this is me here
hi this   is me again
hi   this   is me yet again
 hi  this   is     me
 hi   this   "is,  me
$ sed 's/\w\+\(\W\)/was\1/3' words
hi this was me here
hi this   was me again
hi   this   was me yet again
 hi  this   was     me
 hi   this   "was,  me

答案 3 :(得分:0)

在任何类型的sed中:

sed 's/^\([[:blank:]]*[^[:blank:]]\{1,\}[[:blank:]]\{1,\}[^[:blank:]]\{1,\}[[:blank:]]\{1,\}\)[^[:blank:]]\{1,\}\(.*\)$/\1was\2/' words
相关问题