2010-07-18 119 views
3

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

​​

所需的输出:

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 

回答

5

我总是做这样的:符合使用第一和第二个字,然后使用反向引用自行更换。

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

这将失败,因为奇数空格的。 – Anders 2010-07-18 11:43:20

+0

的确,当我尝试它时,它可以在第一行代替,但在后面的代码中没有。 – xyz 2010-07-18 11:50:30

+0

sed's/^ * \([^] * \)\ \ + \([^] * \)\ +是/ \ 1 \ 2是/'file>结果 – Anders 2010-07-18 13:09:57

6

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

$ 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 
+0

+1,awk很好,刚开始阅读awk编程语言。 – Anders 2010-07-18 12:16:24

+0

''''''''和'''之间的1是什么意思? – odessos 2015-03-13 09:28:53

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 
0

在任何类型的sed:

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