0

I have a list of domains matched and piped in through grep with various length but all match the last three records. I'm trying to output all of the non-qualified sub-domains.

I have:

awk -F'.' -v OFS='.' '{$(NF-3)=$(NF-2)=$(NF-1)=""; print $0}' 

my output leaves trailing ...... on the output

Thanks

3
  • source: site.subdomain.xyz.com site.sub.subdomain.xyz.com results: site... site.sub.... desired results: site site.sub
    – carter
    Oct 8, 2014 at 23:01
  • 1
    Please edit your question and include an example of your input data and your desired output.
    – terdon
    Oct 8, 2014 at 23:05
  • Note {print $0} is the default behaviour of awk, so you can write a true condition instead: 1 will do the same. Also, {print} is the same as {print $0}, so you can omit the reference to $0.
    – fedorqui
    Oct 9, 2014 at 13:14

2 Answers 2

2

When producing output, awk obeys the current value of NF. If you want to eliminate the last three fields, just reduce NF by three, such as via NF-=3:

awk -F. -v OFS=. '{NF-=3; print $0}'

Using this with your sample input:

$ echo $'site.subdomain.xyz.com\nsite.sub.subdomain.xyz.com' | awk -F. -v OFS=. '{NF-=3; print $0}'
site
site.sub

Incidentally, a period, ., is not a shell-active character. So, it does not need quoting.

2
  • That is much cleaner. Just curious, does setting the OFS to '.' have any effect here?
    – muru
    Oct 8, 2014 at 23:55
  • 1
    Thank you. Curiously, yes it does: without OFS=., I get space-separated output. This differs from the output using your approach. I suspect that the difference is that your approach operates on the input line as a whole and therefore does not trigger awk into reformatting with a new OFS.
    – John1024
    Oct 9, 2014 at 0:04
0

Try substituting them:

$ awk -F'.' 'sub(FS $(NF-2) FS $(NF-1) FS $NF,"")' <<<"www.cse.iitb.ac.in"
www.cse

I'm not sure why this works and your method doesn't, but according to this unix.com post, that's the way.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .