Search code examples
bashsortingawklowercaseifs

Bash convert file to lowercase and sort


I am trying to write a script that will take in an inputFile, convert it to lowercase, sort it, and then store the results back in the original file. I'm fairly new to bash, so this is the solution I've come up with so far:

awk '{ print tolower($0) }' $inputFile

index=0
for i in `cat $inputFile`
do                   
    tables[${index}]=$i
    index=$(($index + 1))
done

IFS=$'\n' tables=($(sort <<<"${tables[*]}"))
rm -r $inputFile
printf "%s\n" "${tables[@]}" >> $inputFile

The sorting aspect of this works fairly well, but I am unable to store the results of awk to the original inputFile, so the sorted table still includes uppercase letters. I have tried to redirect the output of awk to > inputFile, but this didn't work either.

Sample inputFile:

TABLE.thisisaTABLE
taBLe.hellO
HELLO.table
hi.table

Desired output (back into original inputFile):

hello.table
hi.table
table.hello
table.thisisatable

Solution

  • You can use the -o flag of sort to perform both the sort and the redirection back into the original file:

    awk '{ print tolower($0) }' $inputFile | sort -o $inputFile