0

I need to write some shell script to get all the directory that start with certain letters and save the result list in a txt file

eg.

-all uppercase directory

-all directory that starts with "Ab"

Any suggestion?

0

1 Answer 1

3

All uppercase directories:

shopt -s nullglob
for d in [[:upper:]]*/ ; do
    echo "$d"
done > uppercase-dirs.txt

All directories starting with Ab:

shopt -s nullglob
for d in Ab*/ ; do
    echo "$d"
done > Ab-dirs.txt

For more info see the pattern matching section of the bash manual.

Note you may have directories that contain unusual characters, e.g. newline. In which case echoing each directory to a text file as a new line will give you incorrect results. One way to get around that is to instead use the nul character to separate each directory. You could do this using printf instead:

shopt -s nullglob
for d in Ab*/ ; do
     printf "%s\0" "$d"
done 

Note also that the shopt -s nullglob is necessary to handle the case when there are no matches to the pattern. Without it, Ab*/ would expand to Ab*/ if there were no matches which is not what you want here. With it, Ab*/ expands to the empty string if there were no matches.

For more information see the shopt section of the bash manual.

2
  • Just a little clarification... what is the purpose of shopt in this situation?
    – AndreaF
    Feb 17, 2015 at 2:14
  • @AndreaF Clarification added. Feb 17, 2015 at 2:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.