LS的打印输出| WC -L在带有两个列的TXT文件中

发布于 2025-01-25 09:25:30 字数 434 浏览 2 评论 0原文

我有许多目录中,每个目录中有不同数量的CSV文件。我有兴趣使用各自数量的CSV文件获取这些目录的列表。所以我有这个bash循环。

 for i in 21 22 23
do
ls my/directory/name$i/*csv | wc -l
done

The question is, how do I get a txt file with an output like this?
name21  3
name22 5
name23 2

Where the 1st column corresponds to the name of each directory and the second one corresponds to the number of CSV files in each directory.

I have many directories with different number of CSV files in each of them. I am interested in getting a list of those directories with a their respective number of CSV files. So I have this bash loop.

 for i in 21 22 23
do
ls my/directory/name$i/*csv | wc -l
done

The question is, how do I get a txt file with an output like this?

name21  3
name22 5
name23 2

Where the 1st column corresponds to the name of each directory and the second one corresponds to the number of CSV files in each directory.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

神回复 2025-02-01 09:25:30

您可以将命令的名称和结果呼应到output.txt

for i in 21 22 23
 do
   echo name$i  $(ls my/directory/name$i/*csv | wc -l)
 done > output.txt

You can echo the names and results of your command to output.txt:

for i in 21 22 23
 do
   echo name$i  $(ls my/directory/name$i/*csv | wc -l)
 done > output.txt
近箐 2025-02-01 09:25:30

https://mywiki.wool.org/parsingls 在其中解释了一些风景和解析其输出将产生错误或意外的结果。您会更好地使用数组并计算其中的元素数量。

for i in 21 22 23; do
   files=( my/directory/name$i/*csv )
   echo "name$i ${#files[@]}"
done >output.txt

也许还要注意完成后的重定向,该重定向避免在循环内重复打开和关闭相同的文件。

如果您想在没有数组的Posix sh上移植,请尝试一个函数。

count () {
    echo "$#"
}

for i in 21 22 23; do
    echo "name$i $(count my/directory/name$i/*csv)"
done >output.txt

对于鲁棒性测试,请尝试创建使用有问题的名称的文件

touch my/directory/name21/"file name
with newline".csv my/directory/name22/'*'.csv

https://mywiki.wooledge.org/ParsingLs explains a number of scenarios where using ls and parsing its output will produce wrong or unexpected results. You are much better off e.g. 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.

If you want to be portable to POSIX sh which doesn't have arrays, try a 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文