'grab a argument as regex pattern inside a shell script

This is simple script to run ls with filter :

sh myscript.sh ".pyc"

myscript.sh :

echo "---------------------------"
for i in `ls | grep '.*\.pyc'`; do
    echo "$i"
done

it will do 'ls' and only show *.pyc. Now i want to put that pattern in the argument :

sh myscript.sh ".pyc"

and modify the script :

echo "---------------------------"
for i in `ls | grep '.*\$1'`; do
    echo "$i"
done

But this doesn't work. it returns empty result. How to properly insert that $1 in the regex while inside the shell script ?



Solution 1:[1]

Replace everything with this: printf '%s\n' *"$1".

Or alternatively just run one of printf '%s\n' *.pyc, ls *.pyc, ls -d *.pyc, etc.

You probably want *.pyc (a shell glob/wildcard which expands to all files ending .pyc), as opposed to using grep.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dan