Test if string has non whitespace characters in Ba

2020-06-07 06:37发布

My script is reading and displaying id3 tags. I am trying to get it to echo unknown if the field is blank but every if statement I try will not work. The id3 tags are a fixed size so they are never null but if there is no value they are filled with white space. I.E the title tag is 30 characters in length. Thus far I have tried

echo :$string: #outputs spaces between the 2 ::

if [ -z "$string" ] #because of white space will always evaluate to true

x=echo $string | tr -d ' '; if [ -z "$string" ]; #still evaluates to true but echos :$x: it echos ::

the script

#!bin/bash
echo "$# files";
while [ "$i" != "" ];
do
   TAG=`tail -c 128 "$i" | head -c 3`;
   if [ $TAG="TAG" ]
   then
      ID3[0]=`tail -c 125 "$1" | head -c 30`;
      ID3[1]=`tail -c 95 "$1" | head -c 30`;
      ID3[2]=`tail -c 65 "$1" | head -c 30`;
      ID3[3]=`tail -c 35 "$1" | head 4`;
      ID3[4]=`tail -c 31 "$i" | head -c 28`;
      for i in "${ID3[@]}"
      do
         if [ "$(echo $i)" ] #the if statement mentioned
         then
            echo "N/A";
         else
            echo ":$i:";
         fi
      done
   else
      echo "$i does not have a proper id3 tag";
   fi
   shift;
done

8条回答
Root(大扎)
2楼-- · 2020-06-07 07:20

Many of these answers are far more complex, or far less readable, than they should be.

[[ $string = *[[:space:]]* ]]  && echo "String contains whitespace"
[[ $string = *[![:space:]]* ]] && echo "String contains non-whitespace"
查看更多
Emotional °昔
3楼-- · 2020-06-07 07:21
[[ -z `echo $string` ]]

The backquotes execute the command within; bash line parsing convert tabs and newlines to blanks and joins double blanks. The echo command re-emits this string, which is shrunk to an empty string for the final test by [[ ]]. I think this is the shortest solution which passes the following:

> VAR="$(echo -e " \n\t")"
> [[ -z  `echo $VAR` ]] ; echo $?
0
> VAR="$(echo -e " \na\t")"
> [[ -z  `echo $VAR` ]] ; echo $?
1
> VAR="$(echo -e "aaa bbb")"
> [[ -z  `echo $VAR` ]] ; echo $?
1
> VAR=
> [[ -z  `echo $VAR` ]] ; echo $?
0
查看更多
登录 后发表回答