awkone-liner

What is a Unix oneliner to swap between fields?


I have a file with a list

id1 str1 str2 .. strn
id2 str1 str2 .. strm

(the number of str can vary) and I want a oneliner that transforms it into

str1 str2 .. strn [id]
str1 str2 .. strm [id]

There should be a way with awk to do that, but I don't know how to take "all fields" after $1, when they are of variable length.

My idea would be something like

cat file | awk '{ print $2 and the rest " [" $1 "]" }'

but just missing the "$2 and the rest"....


Solution

  • $ awk '{for(i=2;i<=NF;i++)printf "%s%s",$i,OFS (i==NF?"[" $1 "]" ORS:"")}' file
    

    Output:

    str1 str2 .. strn [id1]
    str1 str2 .. strm [id2]