Suppress output to StdOut when piping echo

2020-07-26 11:05发布

问题:

I'm making a bash script that crawls through a directory and outputs all files of a certain type into a text file. I've got that working, it just also writes out a bunch of output to console I don't want (the names of the files)

Here's the relevant code so far, tmpFile is the file I'm writing to:

for DIR in `find . -type d` # Find problem directories
do
        for FILE in `ls "$DIR"` # Loop through problems in directory
        do
                if [[ `echo ${FILE} | grep -e prob[0-9]*_` ]]; then
                        `echo ${FILE} >> ${tmpFile}`
                fi
        done
done

The files I'm putting into the text file are in the format described by the regex prob[0-9]*_ (something like prob12345_01)

Where I pipe the output from echo ${FILE} into grep, it still outputs to stdout, something I want to avoid. I think it's a simple fix, but it's escaping me.

回答1:

All this can be done in one single find command. Consider this:

find . -type f -name "prob[0-9]*_*" -exec echo {} >> ${tmpFile} \;

EDIT:

Even simpler: (Thanks to @GlennJackman)

find . -type f -name "prob[0-9]*_*" >> $tmpFile


回答2:

To answer your specific question, you can pass -q to grep for silent output.

if echo "hello" | grep -q el; then
  echo "found"
fi

But since you're already using find, this can be done with just one command:

find . -regex ".*prob[0-9]*_.*" -printf '%f\n' >> ${tmpFile}

find's regex is a match on the whole path, which is why the leading and trailing .* is needed.

The -printf '%f\n' prints the file name without directory, to match what your script is doing.



回答3:

what you want to do is, read the output of the find command,
for every entry find returned, you want to get all (*) the files under that location
and then you want to check whether that filename matches the pattern you want
if it matches then add it to the tmpfile

while read -r dir; do
    for file in "$dir"/*; do  # will not match hidden files, unless dotglob is set
        if [[ "$file" =~ prob[0-9]*_ ]]; then
            echo "$file" >> "$tmpfile"
        fi
done < <(find . -type d)

however find can do that alone
anubhava got me there ;)
so look his answer on how that's done