简体   繁体   中英

Need help editing a script

I want to create a script that takes the directory name as input and then parses through all the sub-directories in that directory and displays the count of the files in each sub-directory that have the date entered (in YYYYMMDD format) in the filename.

Right now I have this:

#!/bin/bash

clear

echo "Please enter date in YYYYMMDD format ";
read date;
dirList=`ls -d *`
for d in $dirList ; do
  count=`find $d -name "*$date*" | wc -l`
  echo $d : $count
done

This just pareses through all the sub-directories in the current directory and displays the solution correctly. How should I edit it to take input of the directory path and do the same in that directory?

You want to know how to (1) read a directory name (from stdin, presumably, as that's where you're getting your input from), and (2) use that directory for the duration of your script's execution?

Nothing simpler:

read -p "Please enter directory to start from: " dir
cd "$dir" || exit

That said, the rest of the script could stand some bugfixing as well:

for d in */; do
  count=$(find "$d" -name "*${date}*" -printf '\n' | wc -l)
  echo "$d: $count"
done

Using ls -d * was buggy in several respects:

  • It didn't actually limit itself to directories
  • It string-split the results of ls , considering a directory named dir with four words to be four separate directories, dir , with , four and words
  • It wasn't guaranteed to work correctly with directories containing nonprintable characters in their names (for which ls implementations' behavior differs).

Similarly, echo $d : $count is buggy due the lack of quotes:

  • A directory named dir with * wildcard would have the * expanded into a list of all files and directories in the current directory.
  • A directory with a tab in its name, or a run of several spaces, would have that information lost.

Similarly, find "$d" -name "*${date}*" | wc -l find "$d" -name "*${date}*" | wc -l isn't guaranteed to be an accurate count either: If a filename contains newlines in its name, some implementations of find will include those in its output as literals, causing wc to count that file multiple times (for each newline); hence the -printf '\\n' to print only a single newline, and not a name at all, for each file identified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM