测试字符串在Bash中是否包含非空白字符 [英] Test if string has non whitespace characters in Bash
问题描述
我的脚本正在阅读并显示id3标签。我试图让它回应未知如果该字段是空白但我尝试的每个if语句都不起作用。 id3标签是固定大小的,因此它们永远不会为null,但如果没有值,则它们将填充空白区域。 I.E标题标签长度为30个字符。到目前为止,我已经尝试了
echo:$ string:#outputs 2 ::
之间的空格
如果[-z$ string]#因为空格将始终评估为真
x = echo $ string | tr -d'';如果[-z$ string];
#still计算结果为true但是回声:$ x:it echos ::
脚本
#!bin / bash
echo$#files;
而[[$ 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|头4`;
ID3 [4] =`tail -c 31$ i| head -c 28`;我在$ {ID3 [@]}中的
如果[$(echo $ i),则表示
,然后是
回声N / A;
else
echo:$ i:;
fi
done
else
echo$ i没有合适的id3标签;
fi
shift;
做
您可以使用bash的正则表达式语法。
它要求你使用双方括号 [[...]]
,(一般来说更通用)。$
该变量不需要引用。正则表达式本身不得
for str inabc; do
if [[$ str =〜^ \ + $]];然后
echo -e有长度,只包含空格\$ str \
else
echo -e是null还是包含非空格\$ str \
fi
done
输出
有长度,只包含空格
是null或包含非空格abc
是null还是包含非空格
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
You can use bash's regex syntax.
It requires that you use double square brackets [[ ... ]]
, (more versatile, in general).
The variable does not need to be quoted. The regex itself must not be quoted
for str in " " "abc " "" ;do
if [[ $str =~ ^\ +$ ]] ;then
echo -e "Has length, and contain only whitespace \"$str\""
else
echo -e "Is either null or contain non-whitespace \"$str\" "
fi
done
Output
Has length, and contain only whitespace " "
Is either null or contain non-whitespace "abc "
Is either null or contain non-whitespace ""
这篇关于测试字符串在Bash中是否包含非空白字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!