1

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...
  • 1
    if the 'counting variable' is just the line number from the file you can reference the `awk` variable `FNR` (File Record Number); you can also eliminate the `cat file` by feeding the file directly to `awk`, eg: `awk -v n=3 '{ printf "(%s) ", FNR ; for (i=n; i<=NF; i++) printf "%s%s", $i, (i – markp-fuso Jul 15 '21 at 22:08
  • 1
    Note that `read _ _ rest` will put the third-and-later words into `$rest`. You don't need awk, and you don't need arrays. – Charles Duffy Jul 15 '21 at 22:20
  • 1
    (Also, you _really_ don't need `cat`; it's less efficient to run `cat foo | awk ...` than just `awk ... – Charles Duffy Jul 15 '21 at 22:21

1 Answers1

2

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
Shawn
  • 47,241
  • 3
  • 26
  • 60