Splitting a file into multiple files based on 1st column value

I have seen solutions of splitting a file with respect to pattern matching and line matching but what I want is the following.
The scenario is, let’s say I have a file file1

A.B|100|20
A.B|101|20
A.X|101|30
A.X|1000|20
B.Y|1|1

Now I want to split this file into 3 different files just based on the first column where the 1st file would be all the lines containing A.B in the first column, the 2nd file should have all the lines with A.X and so on.

If the first column changes in any way, there should be a new file created for those lines. Is there any way of doing it with bash or awk?

Since there is no way of actually knowing before hand what the first column value is, I wasn’t able to use any feature like split or cut. Thanks for the help in advance!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Try:

awk -F| '{print>$1}' file1

This writes each line to a file named after the first column.

How it works:

  • -F| sets the field separator to |.
  • print>$1 prints the current line to a file whose name is the first field.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x