Reputation: 4196
I'm curious if it is possible to retrieve not only the isolated fields using awk, but also a part of the original string that contains multiple adjacent fields and the enclosed delimiters?
For example, when using awk on
foo.bar.baz.test
with the '.'
delimiter, and telling awk to extract the fields 2 and 3, I want to be able to retrieve
bar.baz
automatically. I know I can re-construct the part of the string later by hand, but that just does not feel right.
Ideas?
Upvotes: 3
Views: 534
Reputation: 195289
I am not very sure if this is what you want :
kent$ echo "foo.bar.baz.test"|awk 'BEGIN{FS=OFS="."}{print $2,$3}'
bar.baz
EDIT
I need to generalize it to an unknown number of fields (no hardcoding $2,$3, but everything starting with say $2 till the end - is that possible?)
see the test below:
kent$ echo "a.b.c.d.e.f.g.h.j.foo.bar"|awk 'BEGIN{FS=OFS="."}{for(i=2;i<=NF;i++)s=i==NF?s $i:s $i OFS;print s}'
b.c.d.e.f.g.h.j.foo.bar
Upvotes: 2
Reputation: 58578
This might work for you:
echo foo.bar.baz.test | awk -F. -vOFS=. '{print $2,$3}'
bar.baz
The ,
in the print command is shorthand for the output field separator(OFS).
Upvotes: 2