1

I'm trying to swap words in each line using sed like so:

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

And this is sed.txt:

FIRST LAST
FIRST LAST
FIRST LAST
FIRST LAST

But it's not working and I'm not sure why, my desired outcome is:

LAST FIRST
LAST FIRST
LAST FIRST
LAST FIRST

I know the example is insignificant but I'd like to understand sed more because I've only been using it for swapping words in their current position without changing positions.

2
  • With GNU sed: sed -E 's/(.*) (.*)/\2 \1/' file Commented Oct 2, 2023 at 23:38
  • 1
    For the given sample, you can also use awk '{print $2, $1}' Commented Oct 5, 2023 at 6:52

1 Answer 1

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

The problem is first comma because in source text you do not have it. Change it:

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

and will work

4
  • 1
    Haha derp, thank you! Commented Oct 2, 2023 at 13:45
  • 2
    Also beware that * matches 0-or-more. You may want to replace it with \{1,\} for 1-or-more. Would make a difference if there were lines starting with space characters. Commented Oct 2, 2023 at 15:57
  • 1
    Note that your expression still inserts a comma at the end of the first field. Commented Oct 3, 2023 at 9:43
  • @Kusalananda, true. I just try to do minimal edit of OP expression. Commented Oct 3, 2023 at 9:57

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.