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 to share