简体   繁体   English

如何在bash中一一读取ls命令列出的文件?

[英]how to read files listed by ls command one by one in bash?

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. ls成功地从指定目录中获取了所有文件,但是无法将文件名一个个地给我。 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. 我想一个接一个地获取它,因为我需要进行一些解析并在某处使用它。

#!/bin/sh

echo Content-type: application/json
echo ""

for output in "ls /home/myComputer/Desktop/*";
do
echo $output
done

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建议。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM