SED expression for swapping columns

Viewed 53

I'm trying to figure out how to swap columns1 with column2 seperated by ':' with a SED expression.

Case example:

column1:column2
column1:column2
column1:column2

I'd like to change to this:

column2:column1
column2:column1
column2:column1

I tried the following, but it just outputs it with no change.

sed 's/\([^ ]*\)[ ][ ^C\([^ ]*\)/\2 \1/' test.txt > test1.txt

I would appreciate the help.

1 Answers

1st solution: Could you please try following. Using OP's attempt of back referencing here.

sed 's/\([^:]*\):\(.*\)/\2:\1/' Input_file

2nd solution: In awk using a temporary variable and swapping values of both the fields.

awk 'BEGIN{FS=OFS=":"} {tmp=$1;$1=$2;$2=tmp} 1' Input_file

OR as per Sundeep's suggestion try simply printing them:

awk 'BEGIN{FS=OFS=":"} {print $2, $1}' Input_file

Why OP's attempt is not working: OP's method of using back references capability is looking Good but in regex OP is looking for space to match which is not present, so we need to mention : as per Input_file and it should work then with little tweak.

Related