How to split a text file based on the content into multiple text files

text processing

I have a text file called CAMS.txt that contains the following:

4153999999999991
4153999999999992
4153999999999993
4153999999999994
4801999999999991
4801999999999992
4801999999999993

I would like to split the CAMS.txt file into 2 files – CAMS1.txt and CAMS2.txt. Their contents are as follows

CAMS1.txt

4153999999999991
4153999999999992
4153999999999993
4153999999999994

CAMS2.txt

4801999999999991
4801999999999992
4801999999999993

It's really splitting the file based on the first 4 digits of the original CAMS.txt file. It will always be 4153 and 4801. I'm new to the unix world =)

Best Answer

awk '/^4153/ {print >"CAMS1.TXT"; next} {print >"CAMS2.TXT"}' CAMS.TXT

There are other ways to do that, another would be using two grep commands

grep "^4153" CAMS.TXT > CAMS1.TXT
grep -v "^4153" CAMS.TXT > CAMS2.TXT

That's less efficient but easier to type, after the first grep is done, you recall it from your shell history (using the "up" arrow key) and makes a few changes. Of course the file is read two times, so don't do that if it is huge.

Related Question