【问题标题】:Count filename characters, then copy those files to another directory计算文件名字符,然后将这些文件复制到另一个目录
【发布时间】:2018-10-08 18:37:46
【问题描述】:

我需要编写一个 bash 脚本,将文件复制到 dir2 中,该脚本将文件名中的字符数与作为脚本参数的给定 int 值相匹配。我尝试做某事,但我根本无法复制文件。

read number

list=`for file in *; do echo  -n "$file" | wc -m; done`

for file in $list

do

if [ $file -eq $number ]

then

cp file dir2

fi

done

【问题讨论】:

  • 文件名是否包含扩展名,是否计入字符数?
  • 不,扩展不需要进入字符数

标签: bash copy character filenames filesize


【解决方案1】:

在您的代码中,list 是文件名长度列表,而不是文件名。所以 $file 只是一个数字。您还错过了$file 上的领先$

您不需要使用wc 程序,您可以使用${#name} 获取变量名的长度。我认为你需要这样的东西:

while [[ $number != +([0-9]) ]]
do
    read -p "Enter number: " number
done

for file in *
do

    if (( ${#file} == $number ))
    then
        cp "$file" dir2
    fi

done

【讨论】:

  • 我认为你的答案比我的好得多;我唯一的建议是使用双括号,也许可以使用read -r。 +1
  • 如果我使用双括号,我会使用(( ${#file} == $number ))[[ ]] 用于模式匹配。 -r 仅在用户输入 \ 字符时才需要,这不合适,因为需要整数 - 无论有没有 -r,输入都是错误的。对$number 进行一些验证会很好。添加
  • 是的,太糟糕了,你不能这样做${#file%*.*},这也可以只匹配没有扩展名的文件名。
猜你喜欢
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
  • 2020-12-22
  • 2017-11-18
  • 2021-03-14
  • 2012-02-15
  • 2017-12-11
相关资源
最近更新 更多