Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Occurrence of a string in all the file names within a folder in Bash

I am trying to make a script which allow me to select files with 2 or more occurrences of a string in their name.

Example:

test.txt      // 1 occurrence only, not ok
test-test.txt // 2 occurrences OK
test.test.txt // 2 occurrences OK

I want the script to return me only the files 2 and 3. I tried like that but this didn't work:

rows=$(ls | grep "test")
for file in $rows
do
        if [[ $(wc -w $file) == 2 ]]; then
                echo "the file $file matches"
        fi
done
like image 205
Grugnas Avatar asked Dec 09 '25 11:12

Grugnas


1 Answers

grep and wc are overkill. A simple glob will suffice:

*test*test*

You can use this like so:

ls *test*test*

or

for file in *test*test*; do
    echo "$file"
done
like image 150
John Kugelman Avatar answered Dec 11 '25 02:12

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!