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 file with plain text. This file contains a list like this:

@"Joe", @"211",
@"Bob Nelson", @"132",
@"Jack Sierra", @"3422",
@"Walt Robert", @"14",

The list goes on and on with thousands of names... I need to switch the elements order and transform this list to

@"211", @"Joe",
@"132", @"Bob Nelson",
@"3422", @"Jack Sierra",
@"14", @"Walt Robert",

How do I do it from terminal?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

This one will work with strings with spaces in it:

sed 's/\(@"[^"]*"\), \(@"[^"]*"\)/\2, \1/' input.txt

How it works:

sed - (s)tream (ed)itor will execute (s)ubstosute command on each line of input,
and replaces \(@"[^"]*"\), \(@"[^"]*"\) with the \2, \1.

The \2 means second match (from the second braces)
The \1 means first match (from the first braces).

Braces must be escaped, so we have \( and \). Inside we look for @ character, then " character and then [^"] any characters different than " repeated anytime and then the " character.

Then we expect , comma followed by the space and similar second group for the \2.

share|improve this answer
    
Yessssssssssssssssssssssss!!!!!!!!!!! You are awesome!!!! Thanks. –  SpaceDog Jan 11 '12 at 22:45

Match the first field, the separator and the second field, and print them out in reverse order. Assuming there can't be commas inside the double quotes:

sed -e 's/\(.*,\)\( \)\(.*,\)/\3\2\1/'

Awk is clumsier here because of the comma at the end of the line. Nonetheless you can do the swap by treating comma plus space or / +/ as the field separator.

awk -F ', ' '{print $2 " " $1 ","}'

If there can be commas inside the quotes, you'll need to match the fields in a way that takes your quote escaping rules (if any) into account.

share|improve this answer
    
Your awk implementation produces double comma separator. Should be awk -F ', ' '{print $2 " " $1 ","}' –  Michał Šrajer Jan 11 '12 at 22:46

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.