【问题标题】:Print the number of characters of every file name using for loop in Mac terminal在 Mac 终端中使用 for 循环打印每个文件名的字符数
【发布时间】:2020-11-20 18:30:57
【问题描述】:

我需要在终端 (Mac) 中使用 for 循环打印目录中每个文件名的字符数。这个目录叫做 lorem,它有 3 个文件:at.txt、lorem.txt 和 sed.txt。

到目前为止,我已经这样做了:

lorem sarahr$ ls
at.txt      lorem.txt   sed.txt
FILES=/Users/sarahr/lab-bash-master/lorem/*
lorem sarahr$ for i in $FILES
> do
> echo '$FILES has' | wc -c
> done
      11
      11
      11

十一三倍是结果,但这不是我需要的。你能帮帮我吗?

【问题讨论】:

  • cat * | wc -c
  • 如果必须使用循环,则使用 print * 循环文件。

标签: bash macos for-loop terminal


【解决方案1】:

假设你有一个目录lorem,文件结构如下:

lorem/
├── at.txt
├── lorem.txt
└── sed.txt

以下 bash 脚本在文件夹内运行时应按要求工作:

for file_name in * ; do echo ${#file_name} ; done

输出:

6
9
7

${#parameter}的文档

参数扩展值的字符长度为 代替。如果 parameter'*''@',则替换的值是 位置参数的数量。如果 parameter 是数组名 下标'*''@',替换的值是 数组中的元素。

【讨论】:

    【解决方案2】:

    首先,cd 到您的文件所在的目录。更改您显示的循环以计算所需文件名的长度($file 变量)。使用echo -n 抑制终端换行符,这会将文件名长度加1。

    cd /Users/sarahr/lab-bash-master/lorem
    for file in * ; do
        echo -n "$file "
        echo -n "$file" | wc -c
    done
    

    输出:

    at.txt 6
    lorem.txt 9
    sed.txt 7
    

    【讨论】:

      猜你喜欢
      • 2018-07-22
      • 2021-03-06
      • 2020-05-01
      • 2015-10-26
      • 1970-01-01
      • 2019-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多