Search code examples
bashfor-loopcat

Bash script getting the items from the third column to the last and enumerating the result


I have a script which needs to read from a file, that file is always made up like:

bench toast pepperoni bacon
fruit berry banana
doom happy winter mountain kiwi

The code below, gets me from the third column to the end of the document, so the result is:

cat file | awk -v n=3 '{ for (i=n; i<=NF; i++) printf "%s%s", $i, (i<NF ? OFS : ORS)}'

pepperoni bacon
banana
mountain kiwi

My question is, how can I implement a counting variable for each element so the result shows as:

(1) pepperoni bacon
(2) banana
(3) mountain kiwi
so on...

Solution

  • One way using GNU userland tools:

    $ cut -d' ' -f 3- input.txt | nl -n ln | sed 's/^\([0-9]*\)[[:space:]]*/(\1) /'
    (1) pepperoni bacon
    (2) banana
    (3) winter mountain kiwi
    

    Alternatively, you can use a variation of your awk script that prints out the NR variable (Or FNR if you want to process multiple files at once):

    $ awk -v n=3 '{
                    printf "(%d) ", NR
                    for (i=n; i<=NF; i++)
                      printf "%s%s", $i, (i<NF ? OFS : ORS)
                  }' input.txt
    (1) pepperoni bacon
    (2) banana
    (3) winter mountain kiwi
    

    (Note removal of the Useless Use Of Cat. Also reformatted for readability).

    Or in pure bash:

    $ lines=0 && while read -r -a fields; do printf "(%d) %s\n" "$((++lines))" "${fields[*]:2}"; done < input.txt
    (1) pepperoni bacon
    (2) banana
    (3) winter mountain kiwi