如果字符串具有非空格字符的bash测试 [英] bash test if string has non whitespace characters
问题描述
我的脚本读取和显示ID3标签。我试图让它呼应未知的,如果该字段为空,但每一个if语句我尝试将无法工作。 ID3标签是一个固定的大小,所以他们永远不能为null,但如果没有,他们都充满了白色的空间价值。即标题标签的长度为30个字符。到目前为止,我已经试过
回响:$字符串:之间#outputs空格2 ::
如果[-z$ string]形式的空白#because将始终为true
X = $回声串| TR -d'';如果[-z$字符串];
#still计算结果为真实的,但回声:$ X:它的回声::
剧本
#!斌/庆典
回声$#文件;
而[$ I=!]
做
TAG =`尾巴-c 128$ I|头-c 3`;
如果[$ TAG =TAG]
然后
ID3 [0] ='尾巴-c 125$ 1|头-c 30';
ID3 [1] ='尾巴-c 95$ 1|头-c 30';
ID3 [2] ='尾巴-c 65$ 1|头-c 30';
ID3 [3] ='尾巴-c 35$ 1|头4`;
ID3 [4] ='尾巴-c 31$ I|头-c 28`;
因为我在$ {ID3 [@]}
做
如果[$(回声$ I)]#系统if语句提到
然后
回声N / A;
其他
回声:$ I;
科幻
DONE
其他
回声$我没有一个正确的ID3标签;
科幻
转移;
DONE
您可以使用bash的正则表达式语法。
它需要你使用双括号 [...]
,(更灵活,在一般情况)。结果
变量不需要被引用。正则表达式本身的不得被引用
在ABC海峡;做
如果[[$海峡=〜^ \\ + $]];然后
回声-e有长度,只包含空白的\\$海峡\\
其他
回声-enull或包含非空白\\$海峡\\
科幻
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屋!