Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix grep multiple character search

Tags:

grep

bash

unix

I'm working on a problem in unix bash where it wants me to get an input from the user and then find if the input is valid (i.e. contains only A-Z a-z and the _ underscore character) and reject anything with a character other than those. For example Space_oddity would be valid while Space_oddity132 would be invalid. I'm having trouble figuring out what the syntax of the grep command would be

if        $1 | grep '[A-Za-z_]'
echo "name is valid"
else
echo "name is not valid"
fi

I think I'm supposed to be using {m,} in the grep command but I'm not able to get the correct syntax despite looking at the list of regex commands. Can anybody help me get the correct syntax or post something that is more helpful in understanding the syntax then what I have found so far?

like image 402
masral Avatar asked Sep 14 '25 23:09

masral


1 Answers

Portable Method

The case statement can accomplish this task and it is POSIX and consequently has the advantage of being portable:

#!/bin/sh
case "$1" in
    *[^[:alpha:]_]* )
        echo "name is not valid" ;;
    *)
        echo "name is valid" ;;
esac

This works because, if $1 contains any unallowed character, that character will match [^[:alpha:]_] and the not valid message will be displayed.

Bash-Only Method 1

Using similar logic but using bash's [[...]] test command:

if [[ $1 = *[^[:alpha:]_]* ]]
then
    echo "name is not valid"
else
    echo "name is valid"
fi

Bash-Only Method 2

Alternatively, as suggested by Benjamin W, we can do a substitution to remove all valid characters and then test if the resulting string is empty or not:

if [[ ${1//[[:alpha:]_]} ]]
then
    echo "Name is not valid"
else
    echo "Name is valid"
fi
like image 168
John1024 Avatar answered Sep 17 '25 15:09

John1024