我已经编写了一个代码来读取文本文件并打印文件中的总选项卡。但我想读取目录中的所有文件并计算每个文件中的选项卡并将结果打印到单个输出文件。我该怎么做?
#!/bin/sh
FILE='unit-1-slide.txt'
TABCOUNT=$(tr -cd '\t' < $FILE | wc -c)
echo $TABCOUNT "tabs in file" $FILE >> output.txt
echo "Done!"
最佳答案
您只需要遍历所有文件,例如:
#!/bin/bash
for file in *; do
if [ -f "$file" ]; then
tabs=$(tr -cd '\t' < "$file" | wc -c);
echo "$tabs tabs in file $file" >> output
fi
done
运行后文件输出如下所示:
8 tabs in file file1
4 tabs in file file2
0 tabs in file file3
3 tabs in file file4
...
注意事项:
你应该总是引用你的变量来处理带有特殊字符(如空格)的文件名,并且检查它是否也是一个文件而不是一个目录是个好主意。
关于linux - 如何计算目录文件中的选项卡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15522277/