Reputation: 11
I am writing a shell script that picks one file at a time and processes them. I want the script to pick files in the ascending order of their modified time.
I used the code below to pick .csv files with a particular filename pattern.
for file in /filepath/file*.csv
do
#mystuff
done
But I expect the script to pick .csv files according to the ascending order of their modified time. Please suggest.
Thanks in advance
Upvotes: 1
Views: 173
Reputation: 345
with your loop "for"
for file in "`ls -tr /filepath/file*.csv`"
do
mystuff $file
done
Upvotes: 0
Reputation: 9855
If you are sure the file names don't contain any "strange" characters, e.g. newline, you could use the sorting capability of ls
and read the output with a while read...
loop. This will also work for file names that contain spaces.
ls -tr1 /filepath/file*.csv | while read -r file
do
mystuff "$file"
done
Note this solution should be preferred over something like
for file in $(ls -tr /filepath/file*.csv) ...
because this will fail if you have a file name that contains a space due to the word-splitting involved here.
Upvotes: 1
Reputation: 2749
You can return the results of ls -t
as an array. (-t sorts by modified time)
csvs=($(ls -t /filepath/file*.csv))
Then apply your for loop.
for file in $csvs
do
#mystuff
done
Upvotes: 0