BashScripts.org
http://bashscripts.org/forum/

awk and sed to replace string between two fields
http://bashscripts.org/forum/viewtopic.php?f=21&t=1779
Page 1 of 1

Author:  dagummit [ Tue Dec 31, 2013 1:44 pm ]
Post subject:  awk and sed to replace string between two fields

I am trying to search for particular words in the beginning of a sentence (they could be many of them) in a file then change the value between particular delimeters.

Example:
From
nomad:knight:these two words are not similar
To
nomad:wonderer:these two words are similar

#Looking to search for "nomad" and change "knight" to "wonderer"

From
brave:weak:these two words are not similar
To
brave:warrior:these two words are similar

#again, searching for "brave" and changing it to "warrior"

The first word could be a number of things, but I would have a list. They are separated by a colon (:). So the colon would be the delimeter.

I have this to pull out the 2nd field, but need to somehow replace it with the better word

Code:
> cat test_file | grep brave | awk -F: '{print $2}'
> weak

Author:  Watael [ Tue Dec 31, 2013 7:47 pm ]
Post subject:  Re: awk and sed to replace string between two fields

hi,

Quote:
The first word could be a number of things, but I would have a list.
what about the second word ?

awk is the tool to use to work on ┬źdelimiter separated values┬╗ (aka fields).

Author:  jsz [ Thu Jan 02, 2014 11:08 am ]
Post subject:  Re: awk and sed to replace string between two fields

corresp.txt # wrote:
brave:warrior
nomad:wonderer

Code:
awk -F: -v OFS=: -v str=' not' 'NR == FNR { a[$1] = $2; next } $1 in a { $2 = a[$1]; sub(str, "", $3) } 1' corresp.txt file

Author:  dagummit [ Wed Jan 22, 2014 1:06 pm ]
Post subject:  Re: awk and sed to replace string between two fields

forgot to post, thanks for the responses!

Page 1 of 1 All times are UTC - 6 hours
© 2000, 2002, 2005, 2007 phpBB Group • http://www.phpbb.com