Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a dump file of a database in the following form

('value1','value2',value3','value4'),('value1','value2',value3','value4'),...

I want first to have each tuple in a single line and next i would like to export only a single value (i.e:value3 from each tuple)

share|improve this question
    
You want to be sure that none of the tuples are split by lines, (...). Awk allows you to redefine the record separator, which here could be ),( rather than \n or \r. –  ChuckCottrill Oct 12 '13 at 0:24

1 Answer 1

up vote 3 down vote accepted

Putting each tuple on a separate line:

sed 's@)\s*,\s*(@)\n(@g' your_file

To apply modifications to the file (instead of printing the modified file to stdout):

sed -i 's@)\s*,\s*(@)\n(@g' your_file

To report only value3 (assuming a modified file):

awk -F',' '{print $3}' <your_new_file

This assumes the values themselves don't contain ,. See Michael's comment below.

To do it all in one go (without modifying the file):

sed 's@)\s*,\s*(@)\n(@g' your_file | awk -F',' '{print $3}'

To simplify the above awk call, I made use of the fact that, given your example, we can split the input on , and value3 will be the 3rd value and have no parens in it. If you had wanted value1 or value4 instead, you can do something like:

sed 's@)\s*,\s*(@)\n(@g' your_file | awk -F',' '{print $1}' | sed 's/[()]//'

This of course assumes your values don't have parens in their content.

share|improve this answer
3  
Note that a naïve solution like the above breaks if the values themselves contain commas. Even so, +1 because you beat me to it. –  Michael Kjörling Oct 11 '13 at 11:56
    
@MichaelKjörling Good point. Added to answer. –  Joseph R. Oct 11 '13 at 11:56
    
i can't understand the meaning of symbol @ at sed –  curious Oct 11 '13 at 12:00
    
@curious sed uses whatever character you put after the s as a pattern separator (see this). In this case I used @ instead of / because I happen to think it's more readable. It's especially helpful if your pattern contains / (e.g. in path names). –  Joseph R. Oct 11 '13 at 12:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.