Bash读取会忽略前导空格 [英] Bash read ignores leading spaces

查看:120
本文介绍了Bash读取会忽略前导空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容的文件a.txt

    aaa
    bbb

当我执行以下脚本时:

while read line
do
    echo $line
done < a.txt > b.txt

生成的b.txt包含以下内容

aaa
bbb

可以看到线条的前导空格已被删除.如何保留前导空格?

It is seen that the leading spaces of lines have got removed. How can I preserve leading spaces?

推荐答案

读取数据的Bash FAQ条目中对此进行了介绍.逐行.

read命令修改每行读取的内容;默认情况下,它将删除所有前导和尾随空格字符(空格和制表符,或IFS中存在的任何空格字符).如果不希望这样,则必须清除IFS变量:

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"

正如查尔斯·达菲(Charles Duffy)正确指出的那样(而我专注于IFS问题而错过了);如果要在输出中看到空格,则在使用该变量时还需要引用该变量,否则外壳将再次删除空格.

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.

read-r参数的使用在上一链接页面顶部的单个句子中涵盖.

The use of the -r argument to read is covered in a single sentence at the top of the previously linked page.

读取的-r选项可防止反斜杠解释(通常用作反斜杠换行符,以在多行上继续).如果没有此选项,则输入中的任何反斜杠都将被丢弃.几乎应该始终将-r选项与read结合使用.

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.

关于使用printf代替echo的情况,在某些情况下,echo的行为在所有环境中都不是可移植的,差异可能很难处理.另一方面,printf是一致的,可以完全可靠地使用.

As to using printf instead of echo there the behavior of echo 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.

这篇关于Bash读取会忽略前导空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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