Awk or sed to create a new file?

I have a line delimited text file containing about 900 lines of data. Each line contains a set of numbers with the user's name at the end. eg.

2792|5750|125|4.0|0.25|||6|2|user1
2802|6000|126|4.0|0.25|||2|3|user2
2801|6000|125|4.0|0.25|||4|4|user2
2805|5500|125|4.5|0.25|||3|2|user1
2805|6250|122|4.5|0.25|||4|7|user3
2811|4750|125|3.0|0.25|||4|2|user1
2828|5750|121|4.0|0.25|||6|2|user2

      

I would like to create three new files: one for each user, containing only their data. (for example, the file for user1 will only contain the first, fourth and sixth lines of the original file). Should I use awk or sed for this?

+3


source to share


3 answers


One of the methods:

awk -F "|" '{ print > $NF }' file

      

Here's the results grep . user*

:



user1:2792|5750|125|4.0|0.25|||6|2|user1
user1:2805|5500|125|4.5|0.25|||3|2|user1
user1:2811|4750|125|3.0|0.25|||4|2|user1
user2:2802|6000|126|4.0|0.25|||2|3|user2
user2:2801|6000|125|4.0|0.25|||4|4|user2
user2:2828|5750|121|4.0|0.25|||6|2|user2
user3:2805|6250|122|4.5|0.25|||4|7|user3

      

Also, some people like to add the file extension. This can be done as follows:

awk -F "|" '{ print > $NF ".txt" }' file

      

+7


source


Why not grep

?



grep user1 bigfile > file_for_user1
grep user2 bigfile > file_for_user2
grep user3 bigfile > file_for_user3

      

+1


source


for THEUSER in `cat file | awk -F'|' '{print $10}' | sort | uniq`; do grep $THEUSER file > $THEUSER; done

      

0


source







All Articles