How do i print out all the files of the current directory that start with the letter "k" ?Also needs to count this files.
I tried some methods but i only got errors or wrong outputs. Really stuck on this as a newbie in bash.
CodePudding user response:
Here is a pure Bash solution.
files=(k*)
printf "%s\n" "${files[@]}"
echo "${#files[@]} files total"
The shell expands the wildcard k*
into the array, thus populating it with a list of matching files. We then print out the array's elements, and their count.
The use of an array avoids the various problems with metacharacters in file names (see e.g. https://mywiki.wooledge.org/BashFAQ/020), though the syntax is slightly hard on the eyes.
As remarked by pjh, this will include any matching directories in the count, and fail in odd ways if there are no matches (unless you set nullglob
to true). If avoiding directories is important, you basically have to get the directories into a separate array and exclude those.
To repeat what Dominique also said, avoid parsing ls
output.
Demo of this and various other candidate solutions: https://ideone.com/XxwTxB
CodePudding user response:
Try this Shellcheck-clean pure POSIX shell code:
count=0
for file in k*; do
if [ -f "$file" ]; then
printf '%s\n' "$file"
count=$((count 1))
fi
done
printf 'count=%d\n' "$count"
- It works correctly (just prints
count=0
) when run in a directory that contains nothing starting with 'k'. - It doesn't count directories or other non-files (e.g. fifos).
- It counts symlinks to files, but not broken symlinks or symlinks to non-files.
- It works with 'bash' and 'dash', and should work with any POSIX-compliant shell.
CodePudding user response:
To start with: never parse the output of the ls
command, but use find
instead.
As find
basically goes through all subdirectories, you might need to limit that, using the -maxdepth
switch, use value 1.
In order to count a number of results, you just count the number of lines in your output (in case your output is shown as one piece of output per line, which is the case of the find
command). Counting a number of lines is done using the wc -l
command.
So, this comes down to the following command:
find ./ -maxdepth 1 -type f -name "k*" | wc -l
Have fun!