joe joe - 3 months ago 9
Bash Question

split numbers in and store them in different files using unix shell script

I have a file called "list.txt" which contains the following rows of numbers.

31056780
31909020
31092320
61093190
61094592
45090280
45902902


I need to now take all the rows starting with "31" and store them in another file call file31.txt take all the rows starting with "61" and store them in file61.txt, take all rows starting with "45" store it in file45.txt

file31.txt will contain.

31056780
31909020
31092320


file61.txt will contain.

61093190
61094592


file45.txt will contain.

45090280
45902902


I tried this command for all 3 but it does not do what i want it to do.

awk -F\" '/31*/ {print $0}' list.txt > file31
awk -F\" '/61*/ {print $0}' list.txt > file61
awk -F\" '/45*/ {print $0}' list.txt > file45

Answer

You can use output redirection inside a single awk script. It can construct the filename by concatenating the first two characters of the line.

awk '{ fn = "list" substr($0, 1, 2) ".txt"; print > fn }' list.txt