开发者

How to replace 3rd word in a line using sed

This is my 3rd post in the process of learning sed. I have a hypothetical requirement. I want to be able to replace 3rd word in each line by 'was', where wor开发者_开发技巧ds are delimited by space(s).

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

Desired output:

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

Could people please help with how to do it with sed. I tried a few executing instructions, but didn't work. Thanks,

Jagrati

I found it! I found it!

Okay, I got the right instruction at last. This works:

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


if you do not care about formatting, this is a simpler approach

$ 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


I always do it like this: match the first and second word using groups, and then replace them with themselves using a backreference.

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


This looks at word boundaries rather than only whitespace so it works when there is punctuation, too. It requires 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


In any type of sed:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜