1

This is regarding a hostfile.

INPUT:

1.2.3.4 foooo00001 foo001 # AIX bar0003 NOSLS NOSLS NOCOMMENT
2.3.4.1 foooo00002 foo002 fooo0002 # Linux bar0003 NOSLS NOSLS NOCOMMENT

OUTPUT:

echo "$INPUT" | awk '{print $(NF-3)";"$2";"$1";"$(NF-2)";"$(NF-1)}'
bar0003;foooo00001;1.2.3.4;NOSLS;NOSLS
bar0003;foooo00002;2.3.4.1;NOSLS;NOSLS

but we need this output:

echo "$INPUT" | awk SOMEMAGIC
bar0003;foooo00001;1.2.3.4;NOSLS;NOSLS;foo001
bar0003;foooo00002;2.3.4.1;NOSLS;NOSLS;foo002;fooo0002

Question: How can we modify the awk to append the aliases (amount could vary, a host can have zero, one, two, etc. aliases)?

Space is the delimiter and the aliases are after the hostnames and always ends with "#".

1

If you like awk try

echo "$INPUT" | \
awk -v OFS=';' '
{for(i=4;$i!="#";i++)
     $3=$3 OFS $i
 print $(NF-3),$2,$1,$(NF-2),$(NF-1),$3}'

Same you can do with GNU sed

echo "$INPUT" | \
sed -r 's/(\S*)( \S* )(.*) # \S* (\S*)( .* )\S*/\4\2\1\5\3/;s/ /;/g'
1

You can try this:

echo "$INPUT" | awk '{ for (i = 1; i < NF; i++) { if ($i ~ /#/) { pos = i; break; } } } { for (i = 3; i < pos; i++) s = s";"$i; print $(NF-3)";"$2";"$1";"$(NF-2)";"$(NF-1)s }' 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.