Is it possible to catch a space in a variable? - shell

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

Related

How to check for space in a variable in bash?

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.

Patter matching variable and string

bash script
Hi! I would like to make a bash script that contolli if the content of a var variable does pattern matching with the string ending with ABC?
You can use the bash builtins:
# with glob patterns
if [[ $var == *ABC ]]; then echo "$var ends with ABC"; fi
# with regular expression
if [[ $var =~ ABC$ ]]; then echo "$var ends with ABC"; fi
You are almost there
var="hellowordABC"
echo $var | grep ".*ABC$"
Or using builtin conditions
[[ $var =~ ABC$ ]] && echo "var ends with ABC"

Shell script check if variable contains spaces

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"

How to check if an argument has a single character in shell

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.

How do i compare 2 strings in shell?

I want the user to input something at the command line either -l or -e.
so e.g. $./report.sh -e
I want an if statement to split up whatever decision they make so i have tried...
if [$1=="-e"]; echo "-e"; else; echo "-l"; fi
obviously doesn't work though
Thanks
I use:
if [[ "$1" == "-e" ]]; then
echo "-e"
else
echo "-l";
fi
However, for parsing arguments, getopts might make your life easier:
while getopts "el" OPTION
do
case $OPTION in
e)
echo "-e"
;;
l)
echo "-l"
;;
esac
done
If you want it all on one line (usually it makes it hard to read):
if [ "$1" = "-e" ]; then echo "-e"; else echo "-l"; fi
You need spaces between the square brackets and what goes inside them. Also, just use a single =. You also need a then.
if [ $1 = "-e" ]
then
echo "-e"
else
echo "-l"
fi
The problem specific to -e however is that it has a special meaning in echo, so you are unlikely to get anything back. If you try echo -e you'll see nothing print out, while echo -d and echo -f do what you would expect. Put a space next to it, or enclose it in brackets, or have some other way of making it not exactly -e when sending to echo.
If you just want to print which parameter the user has submitted, you can simply use echo "$1". If you want to fall back to a default value if the user hasn't submitted anything, you can use echo "${1:--l} (:- is the Bash syntax for default values). However, if you want really powerful and flexible argument handling, you could look into getopt:
params=$(getopt --options f:v --longoptions foo:,verbose --name "my_script.sh" -- "$#")
if [ $? -ne 0 ]
then
echo "getopt failed"
exit 1
fi
eval set -- "$params"
while true
do
case $1 in
-f|--foo)
foobar="$2"
shift 2
;;
-v|--verbose)
verbose='--verbose'
shift
;;
--)
while [ -n "$3" ]
do
targets[${#targets[*]}]="$2"
shift
done
source_dir=$(readlink -fn -- "$2")
shift 2
break
;;
*)
echo "Unhandled parameter $1"
exit 1
;;
esac
done
if [ $# -ne 0 ]
then
error "Extraneous parameters." "$help_info" $EX_USAGE
fi

Resources