Register
It is currently Tue Sep 30, 2014 7:50 am

awk and sed to replace string between two fields


All times are UTC - 6 hours


Post new topic Reply to topic  [ 4 posts ] 
Author Message
 PostPosted: Tue Dec 31, 2013 1:44 pm   

Joined: Tue Apr 19, 2011 11:01 pm
Posts: 36
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


Top
 Profile  
 PostPosted: Tue Dec 31, 2013 7:47 pm   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 549
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).


Top
 Profile  
 PostPosted: Thu Jan 02, 2014 11:08 am   
User avatar

Joined: Wed Jun 08, 2011 8:27 am
Posts: 189
Location: outer Shpongolia
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


Top
 Profile  
 PostPosted: Wed Jan 22, 2014 1:06 pm   

Joined: Tue Apr 19, 2011 11:01 pm
Posts: 36
forgot to post, thanks for the responses!


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 4 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 2 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP