如何使用`而read`(击),以在一个文件中读取的最后一行,如果有在文件的末尾没有新行? [英] How to use `while read` (Bash) to read the last line in a file if there’s no newline at the end of the file?
问题描述
比方说,我有以下的Bash脚本:
同时读取SCRIPT_SOURCE_LINE;做
回声$ SCRIPT_SOURCE_LINE
DONE
我注意到,对于没有在最后一个换行符的文件,这将有效地跳过最后一行。
我搜索周围的解决方案,发现这:
在读到达档案结尾,而不是
端的行的,它读取在
数据并将其分配给变量,
但它有一个非零状态退出。
如果你的循环构造,而
阅读,做的东西;做
而不是测试读出这样
状态直接,检验标志,并有
读命令设置该标志由
循环体内。那样
无论读取退出状态时,
整个循环体运行,因为读
只是命令的列表中的一个
在像任何其他,而不是一个循环
决定是否循环的因素将
获得在所有运行。DONE =假
直到$进行;做
阅读|| DONE = TRUE
#$过程REPLY这里
完成< /path/to/file.in
块引用>我怎么能改写这个解决方案,以使其行为完全一样的,因为我前面已经有,即没有硬编码输入文件的位置
,而
循环?解决方案在你的第一个例子中,我假设你是从的标准输入的阅读。要做到与第二code座一样,你只需要删除重定向和回声$回答:
DONE =假
直到$进行;做
阅读|| DONE = TRUE
回声$ REPLY
DONELet’s say I have the following Bash script:
while read SCRIPT_SOURCE_LINE; do echo "$SCRIPT_SOURCE_LINE" done
I noticed that for files without a newline at the end, this will effectively skip the last line.
I’ve searched around for a solution and found this:
When read reaches end-of-file instead of end-of-line, it does read in the data and assign it to the variables, but it exits with a non-zero status. If your loop is constructed "while read ;do stuff ;done
So instead of testing the read exit status directly, test a flag, and have the read command set that flag from within the loop body. That way regardless of reads exit status, the entire loop body runs, because read was just one of the list of commands in the loop like any other, not a deciding factor of if the loop will get run at all.
DONE=false until $DONE ;do read || DONE=true # process $REPLY here done < /path/to/file.in
How can I rewrite this solution to make it behave exactly the same as the
while
loop I was having earlier, i.e. without hardcoding the location of the input file?解决方案In your first example, I'm assuming you are reading from stdin. To do the same with the second code block, you just have to remove the redirection and echo $REPLY:
DONE=false until $DONE ;do read || DONE=true echo $REPLY done
这篇关于如何使用`而read`(击),以在一个文件中读取的最后一行,如果有在文件的末尾没有新行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!