Breaking a file down of strings, into separate files each based on the first letter. BASH

bashparsingscript

Alright, so I have a file full of thousands of strings. Each one on it's own line. I want to make a script that will allow me to take this file, call it list.txt, and take the items from each line, and place it into separate files based on the first letter or number. As an example, say the first few lines of the file are like this:

cheese
pizza
pepperoni
lettuce
grahamCrackers
0-0Foods
chicken
lentils
1-2Items

I need to break it down into these:

c.txt

cheese
chicken

g.txt

grahamCrackers

l.txt

lettuce
lentils

p.txt

pizza
pepperoni

0.txt

0-0Foods

1.txt

1-2Items

I would like to accomplish this with BASH, on OS X. Thanks.

Oh, if it helps. Items on each line will NEVER have a space, they will always be contained as one word. E.G. (Never Chicken Soup, instead Chicken-Soup)

Best Answer

Try this

OLDIFS=$IFS
IFS='
'
typeset -a file
file=($(cat list.txt))
for i in "${file[@]}"; do
    echo $i >> ${i:0:1}.txt
done
IFS=$OLDIFS

Note, the IFS part is not usually necessary. Also, I tested it on Zsh 4.3.17 on linux and on Bash 4.2.37.

What it does is it declares an array, assigns the contents of the file to that array, then loops over each element of the array, hence each line and echo's that element into the file with the name of the first lettes plus '.txt' appended to it.

Related Question