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.
Related
I have this variable:
>echo $br_name
srxa wan-a1 br-wan3-xa1 0A:AA:DD:C1:F1:A3 ge-0.0.3 srxa wan-a2 br-wan3-xa2 0A:AA:DD:C1:F2:A3 ge-0.0.3
I am trying to create a conditional where it detects whether ge-0.0.3 is repeated more than 1 time in my variable $br_name
For example:
if [[ $br_name has ge-0.0.3 repeated more than one time ]]
then
echo "ge-0.0.3 is shown more than once"
else
:
fi
Bash's =~ is using extended RE.
[Bash-5.2] % check() { local s='(ge-0\.0\.3.*){2,}'; [[ "$1" =~ $s ]] && echo yes || echo no; }
[Bash-5.2] % check 'xxx'
no
[Bash-5.2] % check 'ge-0.0.3'
no
[Bash-5.2] % check 'ge-0.0.3 ge-0.0.3 '
yes
[Bash-5.2] % check 'ge-0.0.3 ge-0.0.3 ge-0.0.3 '
yes
You can use grep -o to print only the matched phrase. Also use -F to make sure that it matches literal characters instead of a regex where . and - are special
if [[ $(echo "$br_name" | grep -Fo ge-0.0.3 | wc -l) -gt 1 ]]; then
echo "ge-0.0.3 is shown more than once"
else
echo "only once"
fi
For more complex patterns of course you can drop -F and write a proper regex for grep
simple word
If your word would be "easy", you can detect the occurrences count with:
echo "123 123 123" | sed "s/123 /123\n/g" | wc -l
In which the word is replace for the same but with \n and then wc count the lines
or you can try one of these:
Count occurrences of a char in a string using Bash
How to count number of words from String using shell
complex
Since your word is "complex" or you will want a pattern, you will need regex:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
https://linuxconfig.org/advanced-bash-regex-with-examples
script.sh
count=0
for word in $1; do
if [[ "$word" =~ .*ge-0\.0\.3.* ]]
then
count=$(($count+1))
fi
done
if [ "$count" -gt "1" ];
then
echo "ge-0.0.3 is shown more than once"
else
if [ "$count" -eq "0" ];
then
echo "ge-0.0.3 is not shown"
else
echo "ge-0.0.3 is shown once"
fi
fi
execution
bash script.sh "srxa wan-a1 br-wan3-xa1 0A:AA:DD:C1:F1:A3 ge-0.0.3 srxa wan-a2 br-wan3-xa2 0A:AA:DD:C1:F2:A3 ge-0.0.3"
grep
With grep you can get the ocurrence count
ocurrences=( $(grep -oE '(ge-0\.0\.3)' <<<$1) )
ocurrences_count=${#ocurrences[*]}
echo $ocurrences_count
Assuming you want to do a literal string match on whole words, not substrings, then this might be what you want:
$ if (( $(grep -oFw 'ge-0.0.3' <<<"$br_name" | wc -l) > 1 )); then echo 'yes'; else echo 'no'; fi
yes
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 tried to check the following case:
#!/bin/bash
line="abc"
if [[ "${line}" != [a-z] ]]; then
echo INVALID
fi
And I get INVALID as output. But why?
It's no check if $line contains only a characters in the range [a-z] ?
Use the regular expression matching operator =~:
#!/bin/bash
line="abc"
if [[ "${line}" =~ [^a-zA-Z] ]]; then
echo INVALID
fi
Works in any Bourne shell and wastes no pipes/forks:
case $var in
("") echo "empty";;
(*[!a-z]*) echo "contains a non-alphabetic";;
(*) echo "just alphabetics";;
esac
Use [!a-zA-Z] if you want to allow upper case as well.
Could you please try following and let me know if this helps you.
line="abc"
if echo "$line" | grep -i -q '^[a-z]*$'
then
echo "MATCHED."
else
echo "NOT-MATCHED."
fi
Pattern matches are anchored to the beginning and end of the string, so your code checks if $line is not a single lowercase character. You want to match an arbitrary sequence of lowercase characters, which you can do using extended patterns:
if [[ $line != #([a-z]) ]]; then
or using the regular-expression operator:
if ! [[ $line =~ ^[a-z]+$ ]]; then # there is no negative regex operator like Perl's !~
Why? Because != means "not equal", thats why. You tell bash to compare abc with [a-z]. They are not equal.
Try echo $line | grep -i -q -x '[a-z]*'.
The flag -i makes grep case insensitive.
The flag -x means match the whole line.
The flag -q means print nothing to stdout, just return 1 or 0.
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 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"