LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   awk or gawk question (http://www.linuxquestions.org/questions/programming-9/awk-or-gawk-question-678828/)

sharky 10-24-2008 10:51 AM

awk or gawk question
 
I'm piping a file to awk in order to filter the required fields. The last column in the file will sometimes have spaces. In the example below consider the 'col4 -i' as the last column.

col1 col2 col3 col4 -i

There are no delimiters in the report except for spaces so having spaces in the last column is a dirty trick. :o)

Anyway, if I want to return from awk $2 and $4 then I will not get all of the last field. I've been looking in my trusty Sed & Awk O'reilly book for a way to return $2,$4 and the remainder of the line but haven't found it. Is there a way to do this with awk?

pwc101 10-24-2008 11:13 AM

Perhaps cut will work?
Code:

... | cut -d" " -f 2,4-
That should print out the second and fourth fields, even if the 4th field contains spaces (or whatever character you specify with the -d flag).

bgeddy 10-24-2008 11:22 AM

Just concatenate the last two together :
Code:

echo "col1 col2 col3 col4 -i" | awk '{print $2,$4$5}'
If there's no $5 it's just ignored.

If you want to keep the space then just insert it :

Code:

echo "col1 col2 col3 col4 -i" | awk '{print $2,$4" "$5}'

sharky 10-24-2008 11:33 AM

Quote:

Originally Posted by bgeddy (Post 3320892)
Just concatenate the last two together :
Code:

echo "col1 col2 col3 col4 -i" | awk '{print $2,$4$5}'
If there's no $5 it's just ignored.

If you want to keep the space then just insert it :

Code:

echo "col1 col2 col3 col4 -i" | awk '{print $2,$4" "$5}'

I think this is it. Some times my last 'field' may have more than one space but I can test that with 'awk {print $#}' | sort | uniq' where I keep increasing # till I have no output. Then I know where to set the last value.

I love one liners.

Thanks,

jan61 10-24-2008 01:29 PM

Moin,

why don't you do the concatenation completely in awk?
Code:

awk ' { last = "";
for (i=4; i<=NF; i++) last=last $i;
print $2, last; } ' /path/to/your/file

Jan


All times are GMT -5. The time now is 03:23 AM.