Home > other >  BASH: How to get files (by find) sorted and line by line into a variable?
BASH: How to get files (by find) sorted and line by line into a variable?

Time:08-01

I need a list of files in the defined directory: find "~/WorkDir" -maxdepth 1 -type f This shall be stored in a variable, line by line and sorted:

~/WorkDir/File1.txt
~/WorkDir/File 2.txt
~/WorkDir/File 9.txt

I tried WorkFiles=$(find "$WorkDir" -maxdepth 1 -type f)but this is one line for all files without sorting.

CodePudding user response:

You may try this:

printf -v WorkFiles '%s\n' ~/WorkDir/*
echo "$WorkFiles"

or

WorkFiles=
for file in ~/WorkDir/*; do
    [[ -f $file ]] && WorkFiles =$file$'\n'
done

if only regular files are of interest.

  • Related