LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   AWK - Beginner brainlock (https://www.linuxquestions.org/questions/programming-9/awk-beginner-brainlock-647897/)

fred2008 06-08-2008 09:37 PM

AWK - Beginner brainlock
 
After a day of reading awk and sed tutorials I've hit the wall on a problem and would appreciate advice from the knowledgeable, please. I don't know my arrays,string or variable substitutions from shinola. It all throws me for a loop.

I've sliced and diced a bunch of stuff from different sources using sed and awk one-liners mainly to produce a file for the next step.

The file is sorted on the first field.
The first field is a 4 digit storage location, the second field is the parts in the location, separated by a whitespace.

The file looks likes this:

1234 78adbcd
1234 hj23part
3456 23another
3456 moreparts
3457 another1
3457 yetanother

I'd like to read the file and produce an output file named by field 1, with contents being the part numbers and a count of the parts. I.E. 1234.txt and when you view the file, a count of the parts and a listing of their numbers as in field 2. The order in which the parts appear within the location is not important.

I can't figure out where to begin so that the first field is read just once and all the parts are tossed into the output file until the storage location number changes.

Any clues or pointers with would be appreciated.

matthewg42 06-08-2008 09:49 PM

This should do it.
Code:

awk '{ print $2 >> $1 ".txt"; }' input_file
If find it difficult to understand how you can have done a whole day's worth of awk and not be able to write this. Maybe it's just the re-direction partr with the ">>"?

fred2008 06-08-2008 10:06 PM

Quote:

Originally Posted by matthewg42 (Post 3178749)
This should do it.
Code:

awk '{ print $2 >> $1 ".txt"; }' input_file
If find it difficult to understand how you can have done a whole day's worth of awk and not be able to write this. Maybe it's just the re-direction partr with the ">>"?

Oh damn, that was easy. I think I overdosed on manuals and was trying to do it the hard way.

Thanks a bunch.

matthewg42 06-09-2008 03:26 AM

Sorry if I sounded snotty.

radoulov 06-09-2008 01:43 PM

Actually,
there's no need for double redirection in awk:

Code:

awk '{ print $2 > $1 ".txt" }' input_file
You may have problems not closing the output file though,
so this will be safer:

Code:

awk '!_[$1]++ { close(fn); fn = $1 ".txt" }
{ print $2 > fn }'  input_file



All times are GMT -5. The time now is 01:53 PM.