循环中的bash字符串长度

时间:2015-04-09 12:13:22

标签: bash

我在循环浏览文件夹并根据文件的长度做一定的条件。我似乎没有那么正确。我评估并输出终端中字符串的长度。

    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个字符的文件进行操作

2 个答案:

答案 0 :(得分:2)

试试这个:

for file in *.zip ; do
  wcout=$(wc -c "$file")
  if [[ ${wcout%% *} -eq 9 ]] ; then 
    # some commands
  fi
done

变量扩展中的%%运算符会删除与之后的模式匹配的所有内容。这是glob模式,而不是正则表达式。

与典型程序员的自然良好感觉相反,BASH中的==运算符比较字符串,而不是数字。

或者(在评论之后)你可以:

for file in *.zip ; do
  wcout=$(wc -c < "$file")
  if [[ ${wcout} -eq 9 ]] ; then 
    # some commands
  fi
done

另外的观察是,如果BASH无法扩展*.zip,因为当前目录中没有ZIP文件,它将通过&#34; * .zip&#34;进入$file并进行循环的单次迭代。这导致wc命令报告的错误。所以建议添加:

if [[ -e ${file} ]] ; then ...

作为预防机制。


评论导致此解决方案的另一种形式(加上我添加了安全机制):

for file in *.zip ; do
  if [[ -e "$file" && (( $(wc -c < "$file") == 9 )) ]] ; then 
    # some commands
  fi
done

答案 1 :(得分:0)

在循环外使用过滤器

ls -1 *.zip \
 | grep -E '^.{9}$' \
 | while read FileName
    do
      # Your action
    done

使用内部过滤器

ls -1 *.zip \
 | while read FileName
    do
      if [ ${#FileName} -eq 9 ]
       then
         # Your action
       fi
    done   

替代ls -1,总是有点危险,find . -name '*.zip' -print [但你需要添加2个char长度或过滤名称形式headin ./并且可能限制当前文件夹深度]