庆典读行不读前导空格 [英] bash read line does not read leading spaces
问题描述
我有文件 A.TXT
与以下内容
AAA
BBB
当我执行下面的脚本,
而读线
做
回声$线
完成< A.TXT> b.txt
生成的 b.txt
包含以下
AAA
BBB
可以看出,线前导空格已经得到删除。
我如何preserve前导空格?
这是覆盖在读取数据Bash的FAQ条目行由行。
读命令修改每一行读取;默认情况下,它会删除所有前导和尾部空格(空格和制表符,或以任何IFS空白字符present)。如果没有需要,IFS变量被清除:
#精确的线条,不修剪
而IFS =读-r线;做
printf的'%s的\\ n'$行
完成< $文件
块引用>正如查尔斯·达菲正确地指出的(我想通过关注
IFS
问题错过了);如果你想看到在输出的空间还需要当您使用它或外壳将再次下降空白引用变量。一些在该片段引用其他差异说明相比原来的code。
使用该
-r
参数来读
是覆盖在一个简单的句子在$顶部p $ pviously链接的页面。
-r选项读取prevents反斜线间pretation(通常用作反斜杠换行符对,继续在多个行)。如果没有这个选项,在输入任何反斜杠将被丢弃。你应该总是使用-r选项与读取。
块引用>至于使用
的printf
而不是回声
出现的行为回声
是,有些遗憾的是,在各种环境下,差异并不一致的可移植性可劲儿对付。的printf
,另一方面是一致的,可以全部使用强劲I have file
a.txt
with following contentaaa bbb
When I execute following script,
while read line do echo $line done < a.txt > b.txt
generated
b.txt
contains followingaaa bbb
It is seen that the leading spaces of lines have got removed.
How can I preserve leading spaces?
解决方案This is covered in the Bash FAQ entry on reading data line-by-line.
The read command modifies each line read; by default it removes all leading and trailing whitespace characters (spaces and tabs, or any whitespace characters present in IFS). If that is not desired, the IFS variable has to be cleared:
# Exact lines, no trimming while IFS= read -r line; do printf '%s\n' "$line" done < "$file"
As Charles Duffy correctly points out (and I'd missed by focusing on the
IFS
issue); if you want to see the spaces in your output you also need to quote the variable when you use it or the shell will, once again, drop the whitespace.Notes about some of the other differences in that quoted snippet as compared to your original code.
The use of the
-r
argument toread
is covered in a single sentence at the top of the previously linked page.The -r option to read prevents backslash interpretation (usually used as a backslash newline pair, to continue over multiple lines). Without this option, any backslashes in the input will be discarded. You should almost always use the -r option with read.
As to using
printf
instead ofecho
there the behavior ofecho
is, somewhat unfortunately, not portably consistent across all environments and the differences can be awkward to deal with.printf
on the other hand is consistent and can be used entirely robustly.这篇关于庆典读行不读前导空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!