Cutting a column and pasting its number

Hello Gurus,
This is my first ever post here. I tried looking for similar material but came up empty handed. Apologies if this is too verbose or if I'm not using the correct formatting.

I have files containing a fixed number of elements per line; separator is a single space. Each line has the number of elements and a line identifier as "prefix". For example, s_04 contains:

4 01 A B D F
4 05 C E 1 xx
(etc.)

What I want is to cut each field in turn, and keep track of which field was cut. For example s_04.cut would contain

4 01 (-1) B D F
4 05 (-1) E 1 xx
4 01 (-2) A D F
4 05 (-2) C 1 xx
4 01 (-3) A B F
4 05 (-3) C E xx
4 01 (-4) A B D
4 05 (-4) C E 1

So far, I'm able to cut each field in turn and append it to the desired output file:

    for i in $(seq 1 $nwords)
    do
         j=$(( i+2 ))
        # remove ith field, append to *.cut
        cut -d' ' -f"$j" --comp ./out/s_"$nwords" >> ./out/s_"$nwords".cut

The problem is I don't know how to construct a pipe in which somehow $j is echoed/pasted/inserted after the first two fields in the output file. I'm using an awk script to generate the cut fields externally and then using cut and paste to insert it. It works but it's clunky and am looking for something more elegant and "unixy"

I would be grateful for any guidance. In case it matters, I'm working in some recent flavor of Ubuntu.

Alejandro

Does the output order matter? Try

awk     '       {for (i=3; i<=NF; i++)  {printf "%s", $1 FS $2 FS "(-"i-2")"
                                         for (j=3; j<=NF; j++) if (i!=j) printf " %s", $j
                                         printf "\n"
                                        }
                }
        ' file
4 01 (-1) B D F
4 01 (-2) A D F
4 01 (-3) A B F
4 01 (-4) A B D
4 05 (-1) E 1 xx
4 05 (-2) C 1 xx
4 05 (-3) C E xx
4 05 (-4) C E 1
1 Like

Wow, that's nice, RudiC. Order doesn't matter (actually it does, but I was going to sort output in the next step anyway.) Thank you!

Another approach, but more as an exercise because it lacks clarity:

awk '{p=$0; n=NF; for(i=3; i<=n ;i++) {$0=p; $i=x; $0=$0; $2=$2 " (-" i-2 ")"; print}}' file | sort -k3,3 -k1,2
1 Like

Thanks, Scrutinizer. It is an appealing one-liner, but it comes at the cost of clarity (at least to my novice eyes). I ended up saving RudiC's code as a stand-alone awk script and then piping its output to sort. Even though this is a "one-off" project and I don't foresee revisiting it again, in a few months it will be nice to be understand the "magic". :wink: