我目前的代码如下:
#!/bin/bash
while IFS= read -r line;
do
byte = $(stat -c%s "$line");
echo "$line : $byte";
done< <(ls *.$1)输出如下:
./scan.sh cpp
./scan.sh: line 4: byte: command not found
arraysum.cpp :
./scan.sh: line 4: byte: command not found
countLines.cpp :
./scan.sh: line 4: byte: command not found
createtext.cpp :
./scan.sh: line 4: byte: command not found
multiproc1.cpp :
./scan.sh: line 4: byte: command not found
myWc.cpp :
./scan.sh: line 4: byte: command not found
test.cpp :基本上,我的代码将采用一种语法,并将根据该语法搜索目录。问题是我想要它打印出“文件名”+“文件的字节大小”,只是我似乎无法做到这一点。
发布于 2018-10-06 20:41:33
在类似bash的Bourne类shell的语法中,赋值中的=符号周围不能有任何空格。
byte=value不过,在这里,解析ls的输出是个坏主意。
你可以直接写下来:
#! /bin/sh -
stat -c '%n: %s' -- *."$1"如果您确实需要一个循环,只需编写:
#! /bin/zsh -
for file in *.$1; do
stat -c '%n: %s' -- $file
done或者如果您必须使用bash:
#! /bin/bash -
shopt -s failglob
for file in *."$1"; do
stat -c '%n: %s' -- "$file"
done发布于 2018-10-07 03:42:34
如果您不太关心确切的输出格式,下面是一个简单的方法,它应该与伯恩壳及其后代(包括bash和ksh)一起工作:
$ for file in *; do if [ -f "$file" ] && [ -r "$file" ]; then wc -c "$file"; fi; done
23 HEAD
111 config
73 description如果您也不太关心错误和角落情况(在这种情况下,祝您好运):
$ for file in *; do wc -c $file; done备注:
(( ))或[[ ]]而不是[ ]。(来源)下面还考虑使用$(wc -c <"$file")而不是`wc -c <"$file"`)。(来源)-f测试看看您所看到的是一个普通文件(不是目录、设备、管道、套接字、tty,或者通常是一些不能用字节表示的奇怪的东西)。-r测试该文件的可读性,即wc有成功的机会;如果您正在查看无法读取的大型文件或文件,请按照原始版本和Stéphane的答案使用stat。"$file"的文件),则必须使用引号( my stuff.txt)。`wc -c <"$file"` (它不会打印文件名)和echo或echo -n (它将打印您想要的任何东西)的一些组合。"$@" (解释)。我同意@stéphane-chazelas的观点,即您不应该解析ls的输出;但是如果您解析了,则不需要过程替代。您可以更简单地阅读命令的输出:
ls | while IFS= read -r之类的
或者,如果您想通过目录递归:
find之类的,-type f -print | while IFS= read -r之类的
或者更好的是:
find之类的,-type f print0 | xargs -o之类的
-print0和xargs -0再次正确处理带有空格或制表符的文件名
https://unix.stackexchange.com/questions/473687
复制相似问题