1745784 Members
3798 Online
108722 Solutions
New Discussion юеВ

Stuck on Awk Statement

 
SOLVED
Go to solution
Nobody's Hero
Valued Contributor

Stuck on Awk Statement

I really have tried to figure this out on my own and I hate having to ask but I am stuck here. I read it but don't understand the option.

I have an input file that looks like:
1234-1234-123-12-1234-11234-123

I am using the "-" as my field separator. I can get the first 3 fields using something like, cat myfile | awk -F- '{ print $1 $2 $3 }'

But I want to treat the 4th,5th,6th and 7th field as one field.
so I would end up with four fields.
$1 $2 $3 [$4 $5 $6 &7]

did I explain that correctly.
well anyway, I cant figure it out and I really did give it a go. any help appreciated

thanks
UNIX IS GOOD
4 REPLIES 4
James R. Ferguson
Acclaimed Contributor
Solution

Re: Stuck on Awk Statement

Hi:

# X="1234-1234-123-12-1234-11234-123"

# echo $X | awk -F"-" '{$4=$4"-"$5"-"$6"-"$7;print $1,$2,$3,$4}'
1234 1234 123 12-1234-11234-123

Regards!

...JRF...
Steven E. Protter
Exalted Contributor

Re: Stuck on Awk Statement

Shalom,

Cool part here is the delimiter.

-F"-"

Want to look at a passwd file, use :

Almost any delimiter can be used. The default for awk is spaces.

awk is a good friend of the sysadmin. Great power.

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
Suraj K Sankari
Honored Contributor

Re: Stuck on Awk Statement

Hi,
>>did I explain that correctly.

Yes you did, in awk $1 means 1st filed $2 means 2nd field and so on
and $0 is for hole line
in your awk you can do is like this way also
$ awk -F "-" '{ print $1" " $2" " $3}'no need to give cat filename

to know more about awk see the below link

http://www.ibm.com/developerworks/library/l-awk1.html

http://www.ibm.com/developerworks/library/l-awk2.html

http://www.grymoire.com/Unix/Awk.html

Suraj
mvpel
Trusted Contributor

Re: Stuck on Awk Statement

Perl is an even better friend of the sysadmin:

$ echo "1234-1234-123-12-1234-11234-123" | \
perl -ne \
'print join(" ", split(/-/, $_, 4));'
1234 1234 123 12-1234-11234-123
$

This can handle an arbitrary number of fields - the "4" as the last argument of split designates the total number of split fields, encompassing the entire remainder of the line in the fourth.

Awk was first written in 1977, and needless to say its capabilities and idiosyncrasies such as the $1 $2 .. $n notation, among many other useful sysadmin tools, inspired Larry Wall's original architecture of Perl in 1987.