0

This question already has an answer here:

I have a scenario where all my file patterns are placed in a text file. Now I need to write a shell script to read each and every file pattern name present in the text file and check it it exists in the directory or not. The output should be written to a log file at final.

#!/bin/ksh
file="/usr/opt/filenames.txt"
mondir=/home/pavan
while read line
do
        # display list of files with the pattern in the monitoring directory
filename=$line
ls -lrt $mondir/$filename*
done <"$file"

The above code is listing the files. But i also need to print the count(number of files for each and every filepattern name.

marked as duplicate by don_crissti, Rahul, Networker, Julie Pelletier, sam Aug 30 '16 at 15:40

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 2
    rather than explaining scenario, please post some input/expected output data. – Rahul Aug 30 '16 at 12:24
  • i have some 10 file names inside a text file(filenames.txt) where each and every file name is in separate line. Now need to read the files names inside that text file and check in a sample directory /usr/opt...... So please help me in writing the code. – user187297 Aug 30 '16 at 12:27
  • 3
    Why the bash tag for a ksh script? – Stéphane Chazelas Aug 30 '16 at 13:36
1
#!/bin/ksh -
file="/usr/opt/filenames.txt"
mondir=/home/pavan
IFS=
while read -r filepattern
do
  set -- "$mondir"/$filepattern*
  if [ "$#" -eq 1 ] && [ ! -e "$1" ] && [ ! -L "$1" ]; then
    printf '%s\n' "$filepattern: 0"
  else
    printf '%s\n' "$filepattern: $#"
    ls -lrtd -- "$@"
  fi
done <"$file"

ksh, like the Bourne shell has that misfeature that when a pattern doesn't match, it expands to itself. Above, we use a test for existence ([ -e "$1" ]) to check if we're in the case of an unmatched pattern, however note that it is not fool-proof.

For instance, for filepattern='[a-z]', if [a-z]* does not match any file, the unexpanded pattern ([a-z]*) may actually refer to the file called [a-z]* (which doesn't match the pattern).

If your ksh is based on recent versions of ksh93, you can fix it with:

#!/bin/ksh -
file="/usr/opt/filenames.txt"
mondir=/home/pavan
IFS=
while read -r filepattern
do
  set -- "$mondir"/~(N)$filepattern*
  printf '%s\n' "$filepattern: $#"
  [ "$#" -eq 0 ] || ls -lrtd -- "$@"
done <"$file"

That ~(N) causes the glob to expand to nothing when it doesn't match (like the N glob qualifier of zsh).

  • IFS= while read -r filepattern do set -- "$mondir"/$filepattern*.trg printf '%s\n' "$filepattern: $#" done <"$file" this code is working for me as expected. Thank you very much. – user187297 Aug 30 '16 at 14:22

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