How to sort a file using loop in Linux Bash ?

In this post, we will look at an interesting script/command to see how to sort a file’s data by using bash for loop instead of sort command.

1.Check out file content.

[root@nglinux ~]# cat newfile1 
dog
cat
lion
yak
bird

2. Sort the file content using traditional sort command easily.

[root@nglinux ~]# sort newfile1 
bird
cat
dog
lion
yak
[root@nglinux ~]# 

3. Now apply two loops and sort the contents of the file.

[root@nglinux ~]# for i in {a..z}; do while read line;  do sml=$(echo $line | sed -rn "s/(.*)/\L&/p"); if [[ $sml =~ ^$i ]]; then echo $line; fi; done < newfile1; done
bird
cat
dog
lion
yak
[root@nglinux ~]# 

The above command can work as an alternate to sort command, however this is not efficient since it uses two loops.

However it is interesting to note how we can play with strings/characters in bash shell.

Leave a Reply

Your email address will not be published.