How to replace third word in string using sed

This is my third post in the process of learning sed. I have a hypothetical requirement. I want to be able to replace the third word in each line with "was", where the words are limited to a space.

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

Required Conclusion:

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

Can people help with how to do this with sed. I tried a few instructions but did not work. Thank,

Jagrati

I found him! I found him!

Well, finally, I got the correct instruction. It works:

sed -e 's/[^ ]*[^ ]/was/3' words
+3
source share
4 answers

if you don't care about formatting, this is an easier 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
+6
source

: , , , .

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

Word boundaries are considered here, not just spaces, so it works when there is punctuation. GNU is required for this 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
+1
source

In any type of sed:

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

Source: https://habr.com/ru/post/1755179/


All Articles