Register
It is currently Wed Oct 01, 2014 12:16 pm

sed: cut if found, replace if not


All times are UTC - 6 hours


Post new topic Reply to topic  [ 2 posts ] 
Author Message
 PostPosted: Thu May 03, 2012 12:13 pm   

Joined: Thu May 03, 2012 12:00 pm
Posts: 1
Hi All,

I would want to make a one liner (sed) that is able to extract a field form a log file bounded by two strings, however I wouldn't want to delete those lines that doesn't have this field but have an newline ( or a string, if possible) instead.
This would be particularly important since I would want to use paste command to generate a csv file from several files, each containing the value of the field.

For example

Input file:
Quote:
20120320 [field1,value1]
20120321 [field2,value2]
20120322 [field1,value3][field2,value4]


The expected output file would be
Quote:
value1

value3


The version I made for this purpose was:

Code:
leftPattern="[field1,"
rightPattern="]"
cat infile | psed "s/.*$leftPattern//g" | psed "s/$rightPattern.*//g" > outfile


but it ceratinly does rabish for line beginning with 20120321.

I guess this is not a very common use-case for sed, my gut feeling says branching is the solution but
I haven't found any reasonable track to follow yet.
Does anybody have a clue?
Thank you very much in advance,

Lev


Top
 Profile  
 PostPosted: Thu May 03, 2012 7:31 pm   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 549
hi,

Code:
sed '/\[field1,/! s/.*//; s/.*\[field1,\([^[]*\)].*/\1/' infile
there are links to resources at the end of sed's manpage.


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

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 3 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