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
-all uppercase directory
-all directory that starts with "Ab"
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
All uppercase directories:
shopt -s nullglob for d in [[:upper:]]*/ ; do echo "$d" done > uppercase-dirs.txt
All directories starting with
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.