Well, the last field in word1,word2,word3,a,b,c,d,e
is e
and the third field is word3
. It looks like you want the part of the line starting with the third field. It's easier with cut
:
$ echo word1,word2,word3,a,b,c,d,e | cut -d , -f 3-
word3,a,b,c,d,e
-f 3-
is -f x-y
for fields x to y, but with y
omitted, so it's from 3rd to last field.
Note that it assumes the lines contain at least 3 fields. It would give empty output lines for input lines that contain 2 fields, and leave the line untouched if it contained no comma (you can add a -s
option to skip the non-delimited lines):
$ printf '%s\n' a a,b a,b,c a,b,c,d | cut -d , -f 3-
a
c
c,d
$ printf '%s\n' a a,b a,b,c a,b,c,d | cut -sd , -f 3-
c
c,d
With awk
, you could do:
$ printf '%s\n' a a,b a,b,c a,b,c,d | awk 'sub(/^[^,]*,[^,]*,/, "")'
c
c,d
(the awk 'sub(/^([^,]*,){2}/, "")'
variant, though POSIX, is less portable as there are still a few awk
implementations that don't support the {x,y}
regexp operator)
To delete the first 2 fields (and only print the lines where they have been removed), though that would be using awk
as a glorified sed
as that's the same as sed -n 's/^[^,]*,[^,]*,//p'
.
Or:
$ printf '%s\n' a a,b a,b,c a,b,c,d | awk 'sub(/^[^,]*,?[^,]*,?/, "")'
c
c,d
to print an empty line for lines that have fewer than 3 fields.
cut
:echo word1,word2,word3,a,b,c,d,e | cut -d, -f3-