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

You could just use gawk and simplify things:

gawk '{n=substr($1,0,1); print >> n".txt"}' file.txt
  • n=substr($1,0,1) takes a substring of length 1 starting from the first position (0) of the first field ($1) and saves it into a variable called n.

  • print >> n".txt" will append (>>) each line into a text file called n.txt (where n is the first letter).

To do the same thing for the first two letters, just change the length of substr:

gawk '{n=substr($1,0,2); print >> n".txt"}' file.txt

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.