Reputation: 429
I need to write a bash script which lists all files in a directory (and its subdirectories) that start with a certain letter, say A/a. How can it be done if the content of the file should begin with the letter, rather than its name?
Upvotes: 1
Views: 1185
Reputation: 52291
With just Bash and the globstar
option (shopt -s globstar
) to enable **/*
:
for file in **/*; do [[ $(< "$file") == [Aa]* ]] && echo "$file"; done
This loops through all files (and directories) recursively and checks if their content starts with A
or a
. If so, the filename gets printed.
It actually also tries to compare directories to [Aa]*
, but just returns a non-successful exit status for $(< "$file")
when $file
is a directory.
Alternatively, without Bashsims, using find
:
find . -type f -exec sh -c '[ "$(head -c 1 "$1" | tr A a)" = a ]' _ {} \; -print
This filters for files (-type f
), then spawns a subshell, in which the test "$(head -c 1 "$1" | tr A a)" = a
is run (get first character of file, transpose potential uppercase A
to a
, compare to a
, and if the exit status of that is successful, print the file name.
Upvotes: 2
Reputation: 5298
grep -rn "^[A|a]" * | awk -F: '$2==1{print $1}'
grep recursively(-r
) for the pattern ^[A|a]
in the current folder. If found (need not be on the first line), grep output would look like filname:linenumber:match
. Use awk
with :
as field seperator and for cases where linenumber is 1
(match found on the first line, i.e file beginning), print the 1st
field which is the filename. grep output will contain the linenumber since we r giving the -n
option.
Upvotes: 1