I am new to shell scripting. I have a variable containing path to specific file. I want to check if this variable has any spaces in it.
I tried with
if [[ ${VAR} = "${VAR% *}" ]] ; then
echo "contains spaces"
else
echo "doesnot contain spaces"
fi
But it doesn't work. Any help will be really appreciable.
or
case ${VAR} in
*\ * ) echo "VAR=$VAR has at least one space char" ;;
* ) echo "VAR=$VAR has no space chars" ;;
esac
IHTH
Good solution but you need to reverse the conditions. ${VAR% *} strips up to the last space, so if it is equal to ${VAR} then there weren't any spaces.
You should escape the first ${VAR} in "" as well in case it is empty.
if [[ "${VAR}" == "${VAR% *}" ]] ; then
echo "doesn't contains spaces"
else
echo "contains spaces"
fi
Another solution:
echo $VAR | grep ".*\s.*" && echo "Space exists" || echo "No space exists"
Related
I am taking baby steps at learning bash and I am developing a piece of code which takes an input and checks if it contains any spaces. The idea is that the variable should NOT contain any spaces and the code should consequently echo a suitable message.
Try this:
#!/bin/bash
if [[ $1 = *[[:space:]]* ]]
then
echo "space exist"
fi
You can use grep, like this:
echo " foo" | grep '\s' -c
# 1
echo "foo" | grep '\s' -c
# 0
Or you may use something like this:
s=' foo'
if [[ $s =~ " " ]]; then
echo 'contains space'
else
echo 'ok'
fi
You can test simple glob patterns in portable shell by using case, without needing any external programs or Bash extensions (that's a good thing, because then your scripts are useful to more people).
#!/bin/sh
case "$1" in
*' '*)
printf 'Invalid argument %s (contains space)\n' "$1" >&2
exit 1
;;
esac
You might want to include other whitespace characters in your check - in which case, use *[[:space:]]* as the pattern instead of *' '*.
You can use wc -w command to check if there are any words. If the result of this output is a number greater than 1, then it means that there are more than 1 words in the input. Here's an example:
#!/bin/bash
read var1
var2=`echo $var1 | wc -w`
if [ $var2 -gt 1 ]
then
echo "Spaces"
else
echo "No spaces"
fi
Note: there is a | (pipe symbol) which means that the result of echo $var1 will be given as input to wc -w via the pipe.
Here is the link where I tested the above code: https://ideone.com/aKJdyN
You could use parameter expansion to remove everything that isn't a space and see if what's left is the empty string or not:
var1='has space'
var2='nospace'
for var in "$var1" "$var2"; do
if [[ ${var//[^[:space:]]} ]]; then
echo "'$var' contains a space"
fi
done
The key is [[ ${var//[^[:space:]]} ]]:
With ${var//[^[:space:]]}, everything that isn't a space is removed from the expansion of $var.
[[ string ]] has a non-zero exit status if string is empty. It's a shorthand for the equivalent [[ -n string ]].
We could also quote the expansion of ${var//[^[:space:]]}, but [[ ... ]] takes care of the quoting for us.
I am using shell to simple String regex match. Here is my shell
#!/bin/sh
MSG="ANK"
PATTERN="([A-Z]{3,5}[-][0-9]{2,5})"
if [ "$MSG" =~ "$PATTERN" ]; then
echo "MATCHED";
else
echo "not";
fi
It is giving error
abc.sh: 6: [: ANK: unexpected operator
How should I fix this?
Making the changes proposed by several contributors in the comments yields:
#!/bin/bash
MSG="ANK"
PATTERN="([A-Z]{3,5}[-][0-9]{2,5})"
if [[ "$MSG" =~ $PATTERN ]]; then
echo "MATCHED";
else
echo "not";
fi
Note the change to bash, the change to [[ and removal of the quotation marks around $PATTERN.
I am trying to figure out how to check to see if the first input will end with .txt. It seems like the standard if statement syntax does not apply to my code based upon the way I am getting the input. Does anyone know the proper syntax for the else if statement in my first if statement in my code?
#!/bin/sh
printf "%b %b\n" "$*"
if [ "$1" = "-help" ]
then
echo "Cool Beans"
elif [ "$1" = "*.txt" ]
then
echo "text recd"
else
echo "first input not valid"
fi
if [ "$2" = "-help" ]
then
echo "help options"
else
echo "second input not valid"
fi
In order for pattern matching to work, can use Bash double-bracketed conditionals (while removing the quotes, which disable the matching) :
elif [[ "$1" = *.txt ]]
You can also use regular expression matching :
elif [[ "$1" =~ [.]txt$ ]]
Note that you must escape the period (or put it in brackets like I did) to prevent its special meaning of "any character" to be disabled, as well as anchor the regex to the end with $ so that you are sure you are matching the extension, not a sub-string inside the file name.
If you want something that is not bash-specific, you can try :
elif [ "${1##*.}" = txt ]
The "${1##*.}" expansion removes the longest string that starts from the beginning of the variable named 1 (could be any variable) and ends with a period, leaving the extension only.
You can also use a case statement for POSIX-compatible pattern matching:
printf "%b %b\n" "$*"
case $1 in
-help) echo "Cool Beans" ;;
*.txt) echo "text recd" ;;
*) echo "first input not valid"
esac
case $2 in
-help) echo "help options" ;;
*) echo "second input not valid" ;;
esac
As the title states? Is it possible? I used the below codes but it cant determine if a variable has a space or not. Hope someone can help me
for file in `ls *.[Pp][Dd][Ff]`
do
var1=`echo "$file" | sed -e "s/.*-\(.*\)-.*/\1/"`
var2="document.num=.*$var1"
var3=`grep -l ${var2} *xml`
case "$var3" in
*\ *)
echo $var3 >> haha
;;
*)
var4=`echo "$var3" | sed -e "s/-.*//"`
varName="$var4.$file"
echo ${var2}
echo $var3
mv $file $varName
;;
esac
Works for me:
var="ab"
#var="a b"
case "$var" in
*\ * ) echo "Has space" ;;
* ) echo "No space" ;;
esac
Depending on which variable is commented out, it prints Has space or No space
Use Bash Regular Expression Tests
If you want to be flexible about how you define whitespace, you can use Bash's built-in regular expression tests. For example:
# Variable has a space.
foo=' '
[[ $foo =~ [[:space:]] ]]; echo $?
0
# Variable has a tab.
foo=$'\t'
[[ $foo =~ [[:space:]] ]]; echo $?
0
# Variable has no whitespace because it's empty.
foo=''
[[ $foo =~ [[:space:]] ]]; echo $?
1
I'm trying to make a script to check if an argument has a single uppercase or lowecase letter, or if its anything else (a digit or a word for example.)
So far got this done:
if echo $1 | egrep -q '[A-Z]';
then echo "Uppercase";
elif echo $1 | egrep -q '[a-z]';
then echo "Lowercase";
else
echo "FAIL";
fi
Need to make it to fail me not only if it isnt a letter, but if I insert a word or 2 letters.
You was very close !
if echo $1 | egrep -q '^[A-Z]$';
then echo "Uppercase";
elif echo $1 | egrep -q '^[a-z]$';
then echo "Lowercase";
else
echo "FAIL";
fi
I've just added the special characters ^ & $, means respectively start of line & end of line
no need egrep there, grep is sufficient
Use case:
case "$1" in
[a-z]) echo First argument is a lower case letter;;
[A-Z]) echo First argument is an upper case letter;;
*) echo First argument is not a single letter;;
esac
If you use bash,
if [[ $1 == [[:upper:]] ]]; then
echo "$1 is a single capital letter"
elif [[ $1 == [[:lower:]] ]]; then
echo "$1 is a single lowercase letter"
else
echo "$1 is not a letter or is more than 1 char"
fi
The double equals tells bash to match against a pattern on the right-hand side.