开发者

Sorting content based on first field and outputting second field into new file

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


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.


awk '{print $2 >> "filename."$1 }' filename

If you want the entire line:

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


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜