Bash while 循环逐行读取文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8571502/
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
Bash while loop that reads file line by line
提问by Narek
There are two ways of reading a file line by line that I want to discuss here:
有两种逐行读取文件的方法,我想在这里讨论:
#!/bin/bash
while read line
do
echo-e "$ line \ n"
done <file.txt
and
和
#!/bin/bash
exec 3<file.txt
while read line
do
echo-e "$ line \ n"
done
So first version works fine but I don't understand the mechanism of working while loop with the file. But the mechanism of the second version I understand. But here I don't understand why it hangs and does not print anything.
所以第一个版本工作正常,但我不明白使用文件进行 while 循环的机制。但是第二个版本的机制我理解。但在这里我不明白为什么它挂起并且不打印任何东西。
采纳答案by Jonathan Leffler
The first loop works because the redirection after the done
applies to the whole loop, so the read
there is reading from the file, not from the standard input of the script.
第一个循环有效,因为 之后的重定向done
适用于整个循环,因此read
从文件中读取,而不是从脚本的标准输入中读取。
The second version hangs because read
reads from file descriptor 0, which is standard input, and you've not typed anything there. The exec
line redirects file descriptor 3 for reading from the file, but you're not reading from file descriptor 3.
第二个版本挂起是因为read
从文件描述符 0 读取,这是标准输入,并且您没有在那里输入任何内容。该exec
行重定向文件描述符 3 以从文件中读取,但您不是从文件描述符 3 中读取。
You could rescue the second by using:
您可以使用以下方法拯救第二个:
exec <file.txt
Now standard input is read from the named file.
现在从命名文件中读取标准输入。
回答by potong
This might work for you:
这可能对你有用:
exec 3<file.txt
while read -u3 line
do
echo -e "$line \n"
done
-u3
reads from file descriptor 3
-u3
从文件描述符 3 读取
Strange that echo
does not have the complement switch like ksh's print
command.
奇怪的是echo
没有像 ksh 的print
命令那样的补码开关。
回答by jaypal singh
There are few mistakes in your scripts.
您的脚本中几乎没有错误。
- Space between
$
and variable name. (may be bad edit) - Space between
echo
and-e
. (may be bad edit) - Mentioning the read at a file descriptor where the file is open. You are reading the file at descriptor 0 and exec is running at descriptor 3.
$
和变量名之间的空格。(可能是不好的编辑)echo
和之间的空间-e
。(可能是不好的编辑)- 在文件打开的文件描述符中提及读取。您正在描述符 0 处读取文件,而 exec 在描述符 3 处运行。
It should be something like this -
应该是这样的——
#!/bin/bash
exec 3<file.txt
while read line
do
echo -e "$line \n"
done <&3
回答by Cristian
-u3 is great for my purpose (reading only the following line)
-u3 非常适合我的目的(仅阅读以下行)
#!/bin/bash
logs=(*Logs.txt)
[[ -e "${logs[0]}" ]] || exit 0
exec 3<"${logs[0]}"
while read -u3 line
do
if [[ $(echo "$line"| grep -c SCSI_STATUS_CHECK_CONDITION) -eq 1 ]]; then
read -u3 line
echo "$line"
fi
done