xyz
xyz

Reputation: 8927

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 words 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

Upvotes: 3

Views: 15459

Answers (4)

djhaskin987
djhaskin987

Reputation: 10077

In any type of sed:

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

Upvotes: 0

Dennis Williamson
Dennis Williamson

Reputation: 360345

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

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 342649

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

Upvotes: 7

Sjoerd
Sjoerd

Reputation: 75629

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/'

Upvotes: 5

Related Questions