0

I have list of file in directory where file name is in hh-mm-ss format of time.

05-31-04.mp4 
05-32-04.mp4 
05-34-04.mp4 
05-33-04.mp4
05-30-00.mp4

I need to sort the file based on the file name

like

05-30-00.mp4
05-31-04.mp4 
05-32-04.mp4 
05-33-04.mp4
05-34-04.mp4 

Right now I am having follwing code to list the file

x=$(find . -name "*.mp4" -printf "%f\n")
for file in $x; do
  echo "File -> $file"
CodeDezk
  • 1,230
  • 1
  • 12
  • 40

1 Answers1

2

That's not an array at all. x is a simple string variable, and looping over it without quoting it will split it on whitespace.

That's problematic if you have file names with spaces or other shell metacharacters in them, but undramatic if your simple file names are representative. In that case, just ... sort.

x=$(find . -name "*.mp4" -printf "%f\n" | sort)
printf "File -> %s\n" $x

Not quoting your string variables comes with a ton of warnings, though. Probably actually do use an array.

readarray -d '' x < <(find . -name "*.mp4" -print0 | sort -z)
printf "File -> %s\n" "${x[@]}"

(readarray requires Bash 4+ so will not work out of the box on MacOS. find -print0 and its companion sort -z is a GNU extension which is not portable to POSIX / non-GNU systems.)

If all the files are in the current directory, find is completely overkill; just use the shell's built-in wildcard expansion, which sorts by default.

printf "File -> %s\n" *.mp4

If you need to loop over the files and do something more useful than just print each, you don't need a variable. Just loop directly over the wildcard expansion.

for file in *.mp4; do
    # This is where we do something more useful than ...
    printf "File -> %s\n" "$file"
done

Notice how you need to quote "$file" inside the loop, too. It will look like it works without quoting when you test it with trivial file names, but break in spectacular and hard-to-debug ways when you run it on real files.

tripleee
  • 175,061
  • 34
  • 275
  • 318