Linux 将 IFS 设置为在换行符上拆分时,为什么需要包含退格键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16831429/
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
When setting IFS to split on newlines, why is it necessary to include a backspace?
提问by user431931
I'm curious as to why the backspace is necessary when setting IFS to split on newlines like this:
我很好奇为什么在将 IFS 设置为在这样的换行符上拆分时需要退格:
IFS=$(echo -en "\n\b")
Why can I not just use this (which doesn't work) instead?
为什么我不能只使用它(这不起作用)呢?
IFS=$(echo -en "\n")
I'm on a Linux system that is saving files with Unix line endings. I've converted my file with newlines to hex and it definitely only uses "0a" as the newline character.
我在使用 Unix 行结尾保存文件的 Linux 系统上。我已经用换行符将我的文件转换为十六进制,它绝对只使用“0a”作为换行符。
I've googled a lot and although many pages document the newline followed by backspace solution, none that I have found explain why the backspace is required.
我在谷歌上搜索了很多,虽然很多页面都记录了换行符后跟退格解决方案,但我没有找到解释为什么需要退格的原因。
-David.
-大卫。
采纳答案by spbnick
Because as bash manual says regarding command substitution:
因为正如 bash 手册所说,关于命令替换:
Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted.
Bash 通过执行命令并用命令的标准输出替换命令替换来执行扩展,并删除任何尾随的换行符。
So, by adding \b
you prevent removal of \n
.
因此,通过添加\b
您可以防止删除\n
.
A cleaner way to do this could be to use $''
quoting, like this:
一种更简洁的方法是使用$''
引用,如下所示:
IFS=$'\n'
回答by Old Pro
It's a hack because of the use of echo
and command substitution.
由于使用echo
和命令替换,这是一个黑客。
prompt> x=$(echo -en "\n")
prompt> echo ${#x}
0
prompt> x=$(echo -en "\n\b")
prompt> echo ${#x}
2
The $()
strips trailing newlines and \b
prevents \n
from being a trailing newline while being highly unlikely to appear in any text. IFS=$'\n'
is the better way to set IFS to split on newlines.
所述$()
条带后新行和\b
防止\n
从被,同时非常不可能出现在任何文本尾随换行符。IFS=$'\n'
是将 IFS 设置为在换行符上拆分的更好方法。
回答by moddie
I just remembered the easiest way. Tested with bash on debian wheezy.
我只记得最简单的方法。在 debian wheezy 上用 bash 测试。
IFS="
"
no kidding :)
不开玩笑:)
回答by taiyebur
Just pressing enter without assigning anything also works. Although, it looks like someone made a mistake and difficult to understand.
只需按 Enter 键而不分配任何内容也可以。虽然,看起来有人犯了错误,难以理解。
IFS=
#This is a line