1828490 Members
2309 Online
109978 Solutions
New Discussion

Awk print question

 
SOLVED
Go to solution
Belinda Dermody
Super Advisor

Awk print question

I have a file that the first 4 fields are variable length and each only have 1 data item/word
FileName Tape#REC# RptName Date and the last field is comments variable length with words. The file is not delimited. I know how to use the printf sequence in awk to format the output for it to look nice, but the last field is comments and could be any number of words or stuff. Is there a way in awk to say use $5, etc ... till the end of the record and print it as one field.
6 REPLIES 6
Craig Rants
Honored Contributor

Re: Awk print question

This may not be exactly what you are looking for but I think it will work. The output will need a little work.

awk '{for (i = NF; i > 4; i--) print $i}'

Good Luck,
C
"In theory, there is no difference between theory and practice. But, in practice, there is. " Jan L.A. van de Snepscheut
Marco Paganini
Respected Contributor
Solution

Re: Awk print question

Hello,

This "one-liner" awk program should do the trick for you:

awk '{ rest=""; for (ix = 5; ix <= NF; ix++) { rest = rest " " $ix } printf("%-10.10s %-10.10s %-10.10s %-10.10s %s\n",$1,$2,$3,$4,rest) }'
You may change the %-10.10s format to something that gives you a better aesthetic result.

Hope it helps,
Paga
Keeping alive, until I die.
Sridhar Bhaskarla
Honored Contributor

Re: Awk print question

James,

Try this way.

If your file is called my_text and the first four fields are fixed (say by "space") then you would do like this

awk '{print substr($0, index($0,$4)) }' my_text

-Sri

You may be disappointed if you fail, but you are doomed if you don't try
Sridhar Bhaskarla
Honored Contributor

Re: Awk print question

Hi (again),

A small correction. Make it $5 in the above awk statement otherwise it will print $4 + the comments.

-Sri
You may be disappointed if you fail, but you are doomed if you don't try
Belinda Dermody
Super Advisor

Re: Awk print question

Thanks for the response, Craigs and Sridhar did not work or provide the output that I was looking for, Marco works great, a long one liner though and I have to change the formating parameters.

Thanks
Sridhar Bhaskarla
Honored Contributor

Re: Awk print question

James,

Probably it would have helped if you provided a sample input file.

If your input file is like this

testfile 23#1212 test.report 11/12/01 this is ofcourse my comment

Then

awk '{print substr($0, index($0,$5)) }' input_file

will print out

this is ofcourse my comment

It's a very simple logic that we are printing the substring starting from $5 (this) no matter what spaces or characters are there later. You don't have to deal with the formatting.

-Sri


You may be disappointed if you fail, but you are doomed if you don't try