且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过在shell脚本读取使用命令行读取输入文件跳过最后一行

更新时间:2023-11-22 13:50:58

读取直到它找到一个换行符或文件的结尾,并返回一个非零退出$如果遇到结束文件c $ C。因此,它很可能为它同时读取一行并返回一个非零的退出code。

read reads until it finds a newline character or the end of file, and returns a non-zero exit code if it encounters an end-of-file. So it's quite possible for it to both read a line and return a non-zero exit code.

因此​​,以下code是不是安全的,如果输入的可能不是由一个换行符终止:

Consequently, the following code is not safe if the input might not be terminated by a newline:

while read LINE; do
  # do something with LINE
done

由于体内的,而不会在最后一行执行。

because the body of the while won't be executed on the last line.

从技术上说,不与新行终止的文件不是文本文件,文本工具可能在这样的一个文件奇方式失败。但是,我总是不愿意依傍这一解释。

Technically speaking, a file not terminated with a newline is not a text file, and text tools may fail in odd ways on such a file. However, I'm always reluctant to fall back on that explanation.

要解决这个问题的方法之一是测试什么读非空( -n

One way to solve the problem is to test if what was read is non-empty (-n):

while read -r LINE || [[ -n $LINE ]]; do
  # do something with LINE
done

其他的解决方案,包括使用映射文件将文件读入一个数组,通过一些实用工具,是保证正确地终止的最后一行通过管道将文件(的grep。,例如,如果你不希望处理空行),或者像 AWK 的工具做迭代处理> (这通常是我的preference)。

Other solutions include using mapfile to read the file into an array, piping the file through some utility which is guaranteed to terminate the last line properly (grep ., for example, if you don't want to deal with blank lines), or doing the iterative processing with a tool like awk (which is usually my preference).

注意 -r 几乎可以肯定是需要在内建;它会导致不reinter preT \\ -sequences输入。

Note that -r is almost certainly needed in the read builtin; it causes read to not reinterpret \-sequences in the input.