1753405 Members
7535 Online
108793 Solutions
New Discussion юеВ

Scripting question

 
SOLVED
Go to solution
jackie baron_1
Regular Advisor

Scripting question

I need a bit of help with scripting.

I have a file that I want to chop up and it's quite straightforward but I can't figure out how to do it in awk.

The text file consists of an FQDN and a OS version number and I want to replicate it so that it's just hostname and OS version. For example:

box1.xyz.com 07.12.00
box2.xyz.com 08.43.01
box3.xyz.co.uk 06.22.02

and I want to just strip that down to:

box1 07.12.00
box2 08.43.01
box3 06.22.02

I've tried catting the file into awk -F ".", etc but I'm braindead today. Can you have awk called within an awk statement?

Thanks for any help.

jackie
6 REPLIES 6
Steven E. Protter
Exalted Contributor
Solution

Re: Scripting question

Shalom jackie

while read -r DL
do
host=$(echo $DL | awk -F. '{print $1}')
part2=$(echo $DL | awk '{print $2}')
echo "$host $part2"

done < file

file is wherever this data is sitting.

SEP
Steven E Protter
Owner of ISN Corporation
http://isnamerica.com
http://hpuxconsulting.com
Sponsor: http://hpux.ws
Twitter: http://twitter.com/hpuxlinux
Founder http://newdatacloud.com
Laurent Menase
Honored Contributor

Re: Scripting question

while read a
do
echo ${a%%.*} ${a#* }
done < inputfile


or
awk ' { split($1,a,"."); printf "%s %s\n" ,a[1], $2 ;}'
Dennis Handly
Acclaimed Contributor

Re: Scripting question

>Laurent: while read a; do

You can simplify by reading two parms:
while read host_ip version; do
echo ${host_ip%%.*} ${version}
done < inputfile
Hein van den Heuvel
Honored Contributor

Re: Scripting question

>> I've tried catting the file into awk -F ".",

( Never cat a file into awk. A waste of time! :-)

The problem with specifying a period as field separator is that whitepsace is no longer a separator. So you need to speciy both.
And then the problem become that there is a variable number of fields, which you can resolve by printing relative to the end.
The awk solution then becomes:

$ awk -F'[. ]' '{print $1,$(NF-2) "." $(NF-1) "." $NF}' tmp.txt
box1 07.12.00
box2 08.43.01
box3 06.22.02

But it is easier to just replace all non-spaces after the first period with nothing:

$ awk '{sub (/\.[^ ]+/,""); print}' tmp.txt
box1 07.12.00
box2 08.43.01
box3 06.22.02

using perl...

$ perl -pe 's/\.[^ ]+//' tmp.txt
box1 07.12.00
box2 08.43.01
box3 06.22.02

or replace everything from the first periods
through the first space, by a space:

$ perl -pe 's/\..*? / /' tmp.txt

Enjoy.
Hein



David DiBiase
Frequent Advisor

Re: Scripting question

How about a sed option

sed 's/\([^.]*\).* \([^ ]*\)/\1 \2/p'
jackie baron_1
Regular Advisor

Re: Scripting question

Thanks so much guys.

Dave, the sed one didn't work but I guess I can tweak it.