views:

73

answers:

3

Hi all,

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
+3  A: 

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/'
Sjoerd
@Sjoerd, This will fail because of the uneven number of whitespaces.
Anders
@Sjoerd: True, when I tried it, this was able to replace in the first line, but not in later ones.
learnerforever
sed 's/^ *\([^ ]*\)\ \+\([^ ]*\) \+is/\1 \2 was/' file > result
Anders
I know, I was demonstrating the approach and I trust that you can tweak the regex yourself.
Sjoerd
+2  A: 

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
ghostdog74
+1, awk is nice, have just begun reading the awk programming language.
Anders
A: 

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
Dennis Williamson