我正在遍历一个文件夹,并根据文件的长度执行某些条件。我似乎不正确。我评估并在终端中输出字符串的长度。
echo $file|wc -c gives me the answer of all files in the terminal.
但是将其合并到循环中是不可能的
for file in `*.zip`; do
if [[ echo $file|wc -c ==9]]; then
some commands
我要在长度为9个字符的文件上进行操作
试试这个:
for file in *.zip ; do
wcout=$(wc -c "$file")
if [[ ${wcout%% *} -eq 9 ]] ; then
# some commands
fi
done
%%
变量扩展中的运算符将删除所有匹配模式的内容。这是全局模式,不是正则表达式。
与典型程序员的天生好习惯相反==
,BASH中的运算符比较字符串而不是数字。
另外(在评论之后),您可以:
for file in *.zip ; do
wcout=$(wc -c < "$file")
if [[ ${wcout} -eq 9 ]] ; then
# some commands
fi
done
进一步的观察是,如果BASH无法扩展,*.zip
因为当前目录中没有ZIP文件,它将将“ * .zip”传递到$file
循环中并进行一次迭代。这导致wc
命令报告错误。因此,建议添加:
if [[ -e ${file} ]] ; then ...
作为预防机制。
注释引出了该解决方案的另一种形式(加上我添加了我的安全机制):
for file in *.zip ; do
if [[ -e "$file" && (( $(wc -c < "$file") == 9 )) ]] ; then
# some commands
fi
done
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句