[英]printing output of ls | wc -l in a txt file with two columns
I have many directories with different number of CSV files in each of them.我有很多目录,每个目录中都有不同数量的 CSV 个文件。 I am interested in getting a list of those directories with a their respective number of CSV files.
我有兴趣获取这些目录的列表,它们各自包含 CSV 个文件。 So I have this bash loop.
所以我有这个 bash 循环。
for i in 21 22 23
do
ls my/directory/name$i/*csv | wc -l
done
name21 3名字21 3
name22 5名字22 5
name23 2名字23 2
You can echo the names and results of your command to output.txt
:您可以将命令的名称和结果回显到
output.txt
:
for i in 21 22 23
do
echo name$i $(ls my/directory/name$i/*csv | wc -l)
done > output.txt
https://mywiki.wooledge.org/ParsingLs explains a number of scenarios where using ls
and parsing its output will produce wrong or unexpected results. https://mywiki.wooledge.org/ParsingLs解释了许多使用
ls
并解析其 output 会产生错误或意外结果的场景。 You are much better off eg using an array and counting the number of elements in it.例如,使用数组并计算其中元素的数量会更好。
for i in 21 22 23; do
files=( my/directory/name$i/*csv )
echo "name$i ${#files[@]}"
done >output.txt
Perhaps also notice the redirection after done
, which avoids opening and closing the same file repeatedly inside the loop.也许还注意到
done
之后的重定向,这避免了在循环内重复打开和关闭同一个文件。
If you want to be portable to POSIX sh
which doesn't have arrays, try a function.如果你想移植到没有 arrays 的 POSIX
sh
,试试 function。
count () {
echo "$#"
}
for i in 21 22 23; do
echo "name$i $(count my/directory/name$i/*csv)"
done >output.txt
For a robustness test, try creating files with problematic names like对于稳健性测试,请尝试创建名称有问题的文件,例如
touch my/directory/name21/"file name
with newline".csv my/directory/name22/'*'.csv
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.