bash 如何在bash中一一读取ls命令列出的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28937273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to read files listed by ls command one by one in bash?
提问by user3714598
I want to read all the files in a particular directory, and I want to read it one by one.
我想读取一个特定目录下的所有文件,我想一个一个地读取它。
Here's what i've done so far. ls successfully get all the files from a specified directory, but could not give the file names to me one by one. It Echos the files one time only. I want to get it one by one because I need to do some parsing and use it somehwere.
这是我到目前为止所做的。ls 成功获取了指定目录下的所有文件,但是无法一一给我文件名。它只回显文件一次。我想一一得到它,因为我需要做一些解析并在某个地方使用它。
#!/bin/sh
echo Content-type: application/json
echo ""
for output in "ls /home/myComputer/Desktop/*";
do
echo $output
done
回答by aioobe
You can do
你可以做
for output in /home/myComputer/Desktop/*
do
echo $output
done
If there's any risk that /home/myComputer/Desktop
is empty, please follow @JIDs advice in the comments below.
如果有任何/home/myComputer/Desktop
空白的风险,请在下面的评论中遵循@JIDs 的建议。
回答by Walter A
The next solution also works when the dir is empty.
当目录为空时,下一个解决方案也适用。
ls /home/myComputer/Desktop/ 2>/dev/null |while read -r output; do
echo ${output}
done
This construction is nice to know, for when you want to split the input lines in some fields:
这种结构很高兴知道,因为当您想在某些字段中拆分输入行时:
cat someFile | while read -r field1 field2 remainingfields; do