Shell脚本以升序显示文件的所有单词
在这里,我们将看到一个 shell 脚本,它将按升序排列文件中的所有单词,当我们有许多单词需要按升序排序时,这会派上用场。该脚本有助于轻松分析数据并以更有条理的方式表示数据。
方法:
- 将文件的值存储到文件名变量中。
- 将单词存储到 TEMP 文件中。
- 使用 sort 命令对单词进行排序。
- 如果 TEMP 文件存在,则将其删除。
例子:
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
Shell脚本如下:
# 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 ascending 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
输入: words.txt 包含 100 个单词。
输出: