Justin Carrey
Justin Carrey

Reputation: 3851

Order of the file reading from a directory in linux

If in a directory, suppose there are 100 files with names like file.pcap1, file.pcap2, file.pcap3,....., file.pcap100. In a shell script, to read these file one-by-one, i have written a line like:

for $file in /root/*pcap*
do
  Something
done

What is the order by which files are read? Are they read in the increasing order of the numbers which are at the end of the file names? Is this the same case for all types of linux machines?

Upvotes: 1

Views: 442

Answers (2)

jfs
jfs

Reputation: 414585

POSIX shell returns paths sorted using current locale:

If the pattern matches any existing filenames or pathnames, the pattern shall be replaced with those filenames and pathnames, sorted according to the collating sequence in effect in the current locale

It means pcap10 comes before pcap2. You probably want natural sorting order instead e.g., Python analog of natsort function (sort a list using a “natural order” algorithm).

Upvotes: 1

Jon Lin
Jon Lin

Reputation: 143906

It is sorted by file name. Just like the default ls (with no flags).

Also, you need to remove the $ in your foreach:

for file in /root/*pcap*

Upvotes: 2

Related Questions