首页 > 解决方案 > 使用 wc 查找文件名的最长长度并分配变量

问题描述

cd subdir1/subdir2

ineedthis=$(find subdir3/ -name "*.csv" | tr ' ' '_') ## assigning name of the file into this variable
echo -n $ineedthis | wc -c

我想通过分配一个名为ineedthis的变量并进行更改以使名称之间没有任何空格来查看所有文件名的长度。然后,我尝试使用 echo -n 仅读取名称并计算字符以查找名称的长度。但是,当我尝试在 echo 语句上使用 wc -c 时,它会给我块的字符数,而不是给我每个文件名的长度。

我希望的是:

# numbers indicating the length of filename

9 subdir3/saying/hello.csv
6 subdir3/saying/hi.csv
9 subdir3/nay/noway.csv
12 subdir3/nay/nomethod.csv
16 subdir3/nay/you_dont_say.csv

标签: bashunix

解决方案


find subdir3/ -name "*.csv" |\
while read path; do
    $file=$(basename "$path")
    $len=$(echo -n "$file" | wc -c) 
    echo $len "$path"
done
  • while循环遍历找到的每条路径find
  • basename剥离所有内容直到最终(可选后缀也可以删除。bash 提供类似和类似的/bultins )${path##*/}${path%%.csv}

推荐阅读