Skip to content
Related Articles

Related Articles

Improve Article
Shell Script to Display All Words of a File in Ascending Order
  • Last Updated : 28 Mar, 2021

Here we will see a shell script that will arrange all the words from a file in ascending order, which comes in handy when we have many words that need to be sorted in ascending order. The script helps to analyze the data easily and represent it in a much more organized manner.

Approach:

  1. Store the value of the file into a filename variable.
  2. Store the words into a TEMP file.
  3. Sort the words using the sort command.
  4. If TEMP file exists then delete it.

Example: 

There is a File named : words.txt which contain the following word, 

Input: word.txt.



Word.txt contains: creature, assorted, bent.

Output: 

assorted

bent

creature

The Shell Script is given below:

# Shell Script to Display All Words of a File in Ascending Order
# echo is for printing the message
echo -n "Enter name of the file :"
# read file name  
read filename
# condition checking if the file exists
# if file do not exists the print "file does not exist"
if [ ! -f $filename ]
then
   echo "File does not exist"
else
# in for loop we are comparing the words and storing it in TEMP file
for i in $(cat $filename)
do
 echo $i >> "TEMP"
done
# printing the sorted value in acending order
echo "***SORTED WORDS IN ASCENDING ORDER***"
echo "$(sort "TEMP")"
fi
# condition checking if the TEMP file exists
# if the TEMP file already exists then it will delete it
if [ -f "TEMP" ]
then
rm "TEMP"
fi

Input:  words.txt containing 100 words.

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :