尾随换行符和内置的bash'read' [英] Trailing newlines and the bash 'read' builtin

查看:65
本文介绍了尾随换行符和内置的bash'read'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash中,这有效:

In bash, this works:

echo -n $'a\nb\nc\n' | while read x; do echo = $x =; done

while循环3次

= a =
= b =
= c =

但是请想象一个没有常规尾随换行符的文本文件.我认为 read 应该仍然适用于所有三行,但事实并非如此.我得到:

But imagine a text file that doesn't have the conventional trailing newline. I think that read should still work for all three lines, but it doesn't. I just get:

echo -n $'a\nb\nc' | while read x; do echo = $x =; done

= a =
= b =

bash中的帮助阅读并没有真正弄清楚.

The help read in bash doesn't really clarify.

注意:我不需要解决此问题,我可以看到一些自行解决的方法.我很好奇,很想提交错误报告-我通常会尽量尊重那些没有尾随换行符的文件.我在使用-d选项进行读取时遇到了这个问题. read -d" 将在空格而不是换行符之间进行拆分,但是除非最后一行有尾部空格,否则它将错过最后一个条目.

Note: I don't need this resolved, and I can see some ways to fix it myself. I am curious, and I am tempted to file a bug report - I generally try myself to respect files that mightn't have the trailing new line. I came across this when using the -d option to read. read -d " " will split on spaces instead of newlines, but it will miss out on the last entry unless it has a trailing space.

(Ubuntu.GNU bash,版本4.1.5(1)-发行版)

(Ubuntu. GNU bash, version 4.1.5(1)-release)

推荐答案

$ man bash
   read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
          One line is read from the standard input, ...

我认为关键是:如何定义一行" .
末尾没有'\ n'的文本是否使一行?
我想 read 不这么认为.

I think the key is: How to define "One line".
Does text without a '\n' at the end makes One line?
I guess read don't think so.

这篇关于尾随换行符和内置的bash'read'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆