简体   繁体   中英

Bash - alternative for: ls | grep

I use the following pipe as variable in a script:

match=$( ls | grep -i "$search")

this is then used in an if statement :

if [ "$match" ]; then
    echo "matches found"
else
    echo "no matches found"
fi

what would be an alternative if I did not want to use find? ShellCheck recommends:

ls /directory/target_file_pattern

but I do not get the syntax right to get the same result. also I want no output when there are no matches for the if statement to work.

If you just want to tell if there exist any matches with bash you could use the builtin compgen like so:

if compgen -G 'glob_pattern_like_your_grep' >/dev/null; then
    echo "matches found"
else
    echo "no matches found"
fi

if you want to operate on the files that are matched, find is usually the right tool for the job:

find . -name 'glob_pattern_like_your_grep' -exec 'your command to operate on each file that matches'

the key though is that you have to use glob patterns , not regex type patterns.

If your find supports it, you might be able to match a regex like

find . -regex 'pattern'

and use that in either the if or with -exec

Use find :

match="$(find . -path "*${search}*" -printf "." | wc -c)"

$match will contain the number of matches. You can check it like this:

if [ "${match}" -gt 0 ] ; then
    echo "${match} files found"
else
    echo "No files found"
fi

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