locklockM
locklockM

Reputation: 139

How I can convert bash into sh

I want to use regex expression, it works in bash, but in sh

str=9009
for i in *v[0-9][0-9][0-9][0-9].txt; do echo "$i";      
       if ! [[ "$i" =~ $str ]]; then rm "$i" ; fi    done

file name like this : mari_v9009.txt femme_v9009.txt mari_v9010.txt femme_v9010.txt, mari.txt, femme.txt

So I want to remove these files : mari_v9010.txt femme_v9010.txt

Upvotes: 0

Views: 192

Answers (1)

Ed Morton
Ed Morton

Reputation: 204124

This might be what you're looking for:

case $i in
    *"$str"* ) # do nothing
        ;;
    * ) rm "$i"
        ;;
esac

From your comments it sounds like you're actually asking for help with more than the regexp that's in your if statement. Try this:

str=9009
for i in ./*v[0-9][0-9][0-9][0-9].txt; do
    echo "$i" >&2
    if [ -e "$i" ]; then
        case $i in
            *"$str"* )
                echo "match for $str in $i" > &2
                ;;
            * ) echo "no match for $str in $i" >&2
                ;;
        esac
    else
         echo "no file name matching $i in directory" >&2
    fi
done

and change the echos to whatever you like after testing.

Also consider not doing any of the above and doing this instead:

find . -maxdepth 1 -name '*v[0-9][0-9][0-9][0-9].txt' ! -name "*$str*" -exec echo rm {} \;

Upvotes: 4

Related Questions