views:

45

answers:

3

I've got a file which is like this:

 3 EOE
 5 APPLE
 6 NOBODY

i need to parse this and output all with '3' in the first column into filename.3, '4' into filename.4, etc... from the unix prompt

+4  A: 

Something like this should work (I haven't tested it):

while read num rest; do
   echo "$num $rest" >> "filename.$num"
done < inputFile

read will read a line of text, then split it up on whitespace into "words", like when you run a command. It will assign the first "word" to the first variable name (num in this case - which will get the number), the second "word" to the second variable name (rest), and so on. If it runs out of variables, it will append the remainder of the line to the last variable (rest, here).

When read processes a line successfully it returns zero, which is "success" in shell scripting, so the while loop will keep going, reading subsequent lines. When read hits the end of the file, it will return 1, stopping the while loop.

Doug
+3  A: 
awk '{print $2 >> "filename."$1 }' filename

If you want the entire line:

awk '{print $0 >> "filename."$1 }' filename
Wrikken
A: 

using bash for loops, cut and grep

for i in `cut -s -d ' ' -f 1 input.txt`; do
    grep ^$i input.txt > filename.$i
done;
Dave