LinuxQuestions.org
Review your favorite Linux distribution.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 02-01-2012, 05:55 AM   #1
jomann
LQ Newbie
 
Registered: Mar 2011
Posts: 24

Rep: Reputation: 0
Bash / grep regex validation for path names


Hi all,

it's about Bash & regular expressions...

I try to validate the user input of a path.
A valid path looks for instance like this:

//server/sharename
//server-01/share_in/user/
//ser_01-ver/sha-re5

What I have so far:

Code:
if ! echo $share | grep -q -e '[^-0-9A-Z_a-z]' -e '^[^0-9A-Za-z]' \
			-e '[^0-9A-Za-z]$' -e '-_' -e '_-' ; then

echo OK

fi
This validates all constellations of A-Z and 0-9, etc., but I have problems with the "/" (can appear somewhere in the middle and at the end of the path) and "//" (at the beginning of the path, leading double-slashes).

Any help very much appreciated.
Thanks & regards,
jomann.
 
Click here to see the post LQ members have rated as the most helpful post in this thread.
Old 02-01-2012, 07:11 AM   #2
Dr_P_Ross
Member
 
Registered: Nov 2003
Location: Edinburgh, UK
Distribution: Arch
Posts: 43

Rep: Reputation: 18
I think you want something like this:
Code:
if echo $1 | grep -x -E -e  '//[-_A-Za-z0-9]+(/[-_A-Za-z0-9]*)*';
then
 echo ' ok:' $1
else
 echo 'bad:' $1
fi
The -x tells grep to only accept if the whole line is matched. The -E tells grep to use extended regular expressions, thus permitting the use of '+' to mean 'one or more occurrences'. The regular expression expects a double slash, followed by some non-empty text, optionally followed by zero or more path components each starting with a slash.

Of course, this will accept something like '//server_09/////' because a path component may be a slash by itself; up to you whether that is OK.
 
Old 02-01-2012, 07:42 AM   #3
jomann
LQ Newbie
 
Registered: Mar 2011
Posts: 24

Original Poster
Rep: Reputation: 0
Thanks Dr_P_Ross,

this is working nicely for my purpose.

Best regards,
jomann.
 
Old 02-01-2012, 08:47 AM   #4
grail
LQ Guru
 
Registered: Sep 2009
Location: Perth
Distribution: Manjaro
Posts: 9,944

Rep: Reputation: 3168Reputation: 3168Reputation: 3168Reputation: 3168Reputation: 3168Reputation: 3168Reputation: 3168Reputation: 3168Reputation: 3168Reputation: 3168Reputation: 3168
You could also just do it all in bash:
Code:
#!/bin/bash

regex='^//[-_A-Za-z0-9]+(/[-_A-Za-z0-9]*)*'

if [[ $1 =~ $regex ]]
then
	echo yes
else
	echo no
fi
 
2 members found this post helpful.
Old 09-14-2022, 09:08 AM   #5
sailnfool
LQ Newbie
 
Registered: Sep 2006
Posts: 3

Rep: Reputation: 0
Unhappy Tweaking the BASH Regex

I found the regex listed above unsatisfactory since it was not sufficiently generic.
I propose a modification to the regex:
Code:
    bre_filedirname='^([\/-_A-Za-z0-9\.]+[-_A-Za-z0-9\.]*)*$'
I offer a long test program that can be invoked with "bash regex2.sh -v"
However, I am not 100% happy because this expression succeeds when it should fail when presented with the sample:
/abad/file^name

Code:
#!/bin/bash
scriptname=${0##*/}

bre_filedirname='^([\/-_A-Za-z1-9\.]+[-_A-Za-z0-9\.]*)*$'

TESTNAME="Test of function regex (bfunc.regex) from"
TESTNAMELOC="https://github.com/sailnfool/bfunc"
USAGE="\n${0##*/} [-[hv]]\n
\t\tVerifies that the regular expression(s for filedirnames\n
\t\twork correctly.\n
\t\tNormally emits only PASS|FAIL message\n
\t-h\t\tPrint this message\n
\t-v\t\tVerbose mode to show values\n
"

localNUMARGS=0
optionargs="hv"
verbosemode="FALSE"
verboseflag=""
fail=0

while getopts ${optionargs} name
do
	case ${name} in
		h)
			echo -e "${USAGE}" >&2
			if [[ "${verbosemode}" == "TRUE" ]] ; then
				echo -e "${DEBUG_USAGE}" >&2
			fi
			exit 0
			;;
		v)
			verbosemode="TRUE"
			verboseflag="-v"
			;;
		\?)
			echo -e "invalid option: -$OPTARG" >&2
			echo -e "${USAGE}" >&2
			exit 1
			;;
	esac
done

shift $(( ${OPTIND} - 1 ))

if [[ $# -lt ${localNUMARGS} ]] ; then
	echo -e "${0##*/} Insufficient arguments, expcted "\
		"${localNUMARGS}, got $@" >&2
	echo -e "${USAGE}" >&2
	exit 2
fi

declare -a tv
declare -a tt
########################################################################
# tv is short for testvalue
# tt is short for testtype
########################################################################
tv+=("/")
tt+=(${bre_filedirname})

tv+=("//")
tt+=(${bre_filedirname})

tv+=("///")
tt+=(${bre_filedirname})

tv+=("/.")
tt+=(${bre_filedirname})

tv+=("/./")
tt+=(${bre_filedirname})

tv+=("/../.")
tt+=(${bre_filedirname})

tv+=("/usr/bin/b3sum")
tt+=(${bre_filedirname})

tv+=("/etc/dhcp/dhclient.conf")
tt+=(${bre_filedirname})

tv+=("/etc/dhcp/dhclient-exit-hooks.d")
tt+=(${bre_filedirname})

tv+=("/etc/gdm3/config-error-dialog.sh")
tt+=(${bre_filedirname})


for ((ti=0; ti<${#tv[@]}; ti++))
do
	if [[ ! "${tv[${ti}]}" =~ ${tt[${ti}]} ]] ; then
		((fail++))
		if [[ "${verbosemode}" == "TRUE" ]] ; then
			echo -e "Failed Test of ${tv[${ti}]}, " \
				"expected ${tt[${ti}]}" >&2
		fi
	fi
done

declare -a fv
declare -a ft
########################################################################
# fv is short for failvalue
# ft is short for failtype
########################################################################
fv+=("/a bad/filename")
ft+=(${bre_filedirname})

fv+=("/abad/file^name")
ft+=(${bre_filedirname})

########################################################################
# In this case if the pattern match succeeds then it
# is broken
########################################################################
for ((ti=0; ti<${#fv[@]}; ti++))
do
	if [[ "${fv[${ti}]}" =~ ${ft[${ti}]} ]] ; then
		((fail++))
		if [[ "${verbosemode}" == "TRUE" ]] ; then
			echo -e "Failed Test succeeded with "\
				"${fv[${ti}]},\n" \
				"expected fail for ${ft[${ti}]}" >&2
		fi
	fi
done

exit ${fail}

Last edited by sailnfool; 09-14-2022 at 09:12 AM. Reason: Removed -d option as extraneous
 
Old 09-14-2022, 09:40 AM   #6
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 10,636

Rep: Reputation: 5024Reputation: 5024Reputation: 5024Reputation: 5024Reputation: 5024Reputation: 5024Reputation: 5024Reputation: 5024Reputation: 5024Reputation: 5024Reputation: 5024
People….

Don’t do this. If you want to know if a path exists, just “stat” it.
 
Old 09-14-2022, 09:44 AM   #7
astrogeek
Moderator
 
Registered: Oct 2008
Distribution: Slackware [64]-X.{0|1|2|37|-current} ::12<=X<=15, FreeBSD_12{.0|.1}
Posts: 5,950
Blog Entries: 23

Rep: Reputation: 3937Reputation: 3937Reputation: 3937Reputation: 3937Reputation: 3937Reputation: 3937Reputation: 3937Reputation: 3937Reputation: 3937Reputation: 3937Reputation: 3937
@sailinfool - You have replied to a thread that has been dormant for 10+ years, with an example that is not especially relevant to the question.

If you have a problem that you think to be similar, please open your own thread and post a minimal code example which illustrates your specific problem so that those currently active may provide relevant replies.

Please review the Site FAQ for guidance in asking well formed questions. Especially visit the link from that page, How to Ask Questions the Smart Way for discussion of things to consider when asking others for help.

Last edited by astrogeek; 09-14-2022 at 09:47 AM.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
grep regex with wildcard yknot7 Linux - Newbie 6 11-10-2011 01:11 AM
[SOLVED] Combining regex in grep devUnix Linux - General 2 09-06-2011 11:11 AM
Getting directory names from a given path in Bash? ojha_riddhish Programming 10 04-13-2009 05:08 AM
regex in ls vs. grep jhwilliams Linux - Software 2 08-10-2007 10:14 PM
Matching values in a bash script grep, regex's ... ? maxvonseibold Linux - General 6 01-29-2007 06:07 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 05:11 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration