Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Picking input record fields with AWK

Tags:

arrays

awk

Let's say we have a shell variable $x containing a space separated list of numbers from 1 to 30:

$ x=$(for i in {1..30}; do echo -n "$i "; done)
$ echo $x
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

We can print the first three input record fields with AWK like this:

$ echo $x | awk '{print $1 " " $2 " " $3}'
1 2 3

How can we print all the fields starting from the Nth field with AWK? E.g.

4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

EDIT: I can use cut, sed etc. to do the same but in this case I'd like to know how to do this with AWK.

like image 905
haba713 Avatar asked Dec 10 '22 23:12

haba713


1 Answers

Converting my comment to answer so that solution is easy to find for future visitors.

You may use this awk:

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

or pass start position as argument:

awk -v n=3 '{for (i=n; i<=NF; ++i) printf "%s", $i (i<NF?OFS:ORS)}' file
like image 86
anubhava Avatar answered Jan 06 '23 04:01

anubhava