Sidd Sidd - 4 months ago 8
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

^[a-zA-Z0-9]+\.[a-zA-Z]{2,}$


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 ;;
esac


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

Same regex works in BASH also. Consider this snippet:

re='^[a-zA-Z0-9]+\.[a-zA-Z]{2,}$'
s='abc123.xy'

[[ $s =~ $re ]] && echo "${s/./_}"
abc123_xy
Comments