Sorts files in a directory based on a numeric index in the file name… here is a solution to the problem.
Sorts files in a directory based on a numeric index in the file name
I used a for loop in my script, like this….
for var in ipsec_packet*.txt; do
echo $var
done
Output
ipsec_packet10.txt
ipsec_packet11.txt
ipsec_packet12.txt
ipsec_packet13.txt
ipsec_packet14.txt
ipsec_packet15.txt
ipsec_packet16.txt
ipsec_packet17.txt
ipsec_packet18.txt
ipsec_packet1.txt
ipsec_packet2.txt
ipsec_packet3.txt
ipsec_packet4.txt
ipsec_packet5.txt
ipsec_packet6.txt
ipsec_packet7.txt
ipsec_packet8.txt
ipsec_packet9.txt
But I want them to start at 1 in this sort order to the largest available value (here 18)…
ipsec_packet1.txt
ipsec_packet2.txt
...
...
ipsec_packet18.txt
I tried sort -n k14
but it didn’t help. Please suggest me some sort variants that can help me or any other bash/awk feature.
Solution
You can try using sort
with the -V
option for natural sorting of numbers in text:
for var in `ls ipsec_packet*.txt | sort -V`; do echo $var; done