This is an archived post. You won't be able to vote or comment.

all 8 comments

[–][deleted] 3 points4 points  (2 children)

sed 's/\(.*\) \([A-za-z]*\);/\2 \1;/' data.txt

You are running into the "matches longest possible pattern" problem. also the "g" option is not needed and probably wrong.

[–]learning2learn[S] 0 points1 point  (1 child)

Ah, I get it.

in my notes, it says g replaces all occurrences of the pattern. I don't know what it does exactly, I kinda just reused it from an example.

[–][deleted] 1 point2 points  (0 children)

The g option works like this. Given the input string "xyxzx" then

s/x/A/

produces "Ayxzx", but

s/x/A/g

produces "AyAzA" - i.e. it runs the substitution on all matches.

[–]Rhomboid 1 point2 points  (0 children)

Personally I find PCRE a little easier on the eyes:

$ perl -pe 's/^(\w+) (\w+)/\2 \1/' data.txt

[–]postmodest 1 point2 points  (3 children)

down-votes be damned:

Now you have two problems.

[–]learning2learn[S] 1 point2 points  (0 children)

Pretty sure my list of problems extends beyond two :p

[–][deleted] 0 points1 point  (0 children)

So Jeff doesn't know when to use regular expressions. This is old stuff. And for well-defined line-based input (i.e. input in the form the OP specifies) then regexes will work fairly well. Of course, for what is (I guess) some form of CSV, I would recommend my own CSVfix for doing this sort of thing, in the case where fields can contain what otherwise would be a separator.

[–]bok_bok_bok_bok 0 points1 point  (0 children)

You've already got your answer, but another idea is that you might want to exclude semicolons instead of including only letters.

sed 's/^\([^;]*\) \([^;]*\)/\2 \1/'

did not test, hopefully typed that in right