AWK – Print All Columns from Nth to Last with Spaces

awkbashunix

I have the following input file:

a 1  o p
b  2 o p p
c     3 o p p  p

in the last line there is a double space between the last p's,
and columns have different spacing

I have used the solution from: Using awk to print all columns from the nth to the last.

awk '{for(i=2;i<=NF;i++){printf "%s ", $i}; printf "\n"}'

and it works fine, untill it reaches double-space in the last column and removes one space.

How can I avoid that while still using awk?

Best Answer

Since you want to preserve spaces, let's just use cut:

$ cut -d' ' -f2- file
1 o p
2 o p p
3 o p p  p

Or for example to start by column 4:

$ cut -d' ' -f4- file
p
p p
p p  p

This will work as long as the columns you are removing are one-space separated.


If the columns you are removing also contain different amount of spaces, you can use the beautiful solution by Ed Morton in Print all but the first three columns:

awk '{sub(/[[:space:]]*([^[:space:]]+[[:space:]]+){1}/,"")}1'
                                                   ^
                                        number of cols to remove

Test

$ cat a
a 1 o p
b    2 o p p
c  3 o p p  p
$ awk '{sub(/[[:space:]]*([^[:space:]]+[[:space:]]+){2}/,"")}1' a
o p
o p p
o p p  p
Related Question