Sidd Sidd - 1 year ago 70
Bash Question

Check bash script argument against pattern, and replace a character in it

I need to write a bash script that checks if the first argument supplied to the script matches a glob pattern, which in JavaScript RegExp I would express as


In other words: starts with one or more alphabets/digits, followed by exactly one period, followed by 2 or more alphabets, and ends. Everything else should fail the test.

Then I also need to replace the period in the argument with an underscore.

So far I can check if the argument is empty:

case $1 in
'') echo "No argument supplied" >&2; exit 1 ;;

I figure the pattern test would need to be negated and put after the
check in that case statement, but I have no clue how to construct it. Any direct help or online resources would be greatly appreciated.

I would also like any help possible with how I can then change the valid argument supplied to replace the single period in it with an underscore.

Answer Source

Same regex works in BASH also. Consider this snippet:


[[ $s =~ $re ]] && echo "${s/./_}"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download