在bash中迭代文件时保留空格

时间:2015-08-06 13:18:41

标签: bash loops while-loop whitespace

我需要在bash中遍历文本文件的行,我想保留空格。最终目标是提供可能包含空格的this line个短语。

所以,给定一个包含

的phrase_file
xdebug
var_dump
 dump(
pwet
meuh
coin

当我尝试这个时:

while read -r PHRASE
do
    echo "$PHRASE"
done < phrase_file

输出结果为:

xdebug
var_dump
dump(
pwet
meuh
coin

dump()之前的空白去了哪里,我该怎样才能找回来?

3 个答案:

答案 0 :(得分:4)

您可以使用内置的$REPLY变量来捕获整行:

while read -r; do
    echo "$REPLY"
done < phrase_file

请注意,如果您为变量命名(例如示例中的PHRASE),则不会设置$REPLY

答案 1 :(得分:2)

只需将IFS变量设置为空:

while IFS= read -r var;
do
   echo "$var"
done < file

返回:

$ while IFS= read -r var; do echo "$var"; done < file
xdebug
var_dump
 dump(
pwet
meuh
coin

来自How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?

  

IFS =防止修剪前导空格和尾随空格。

答案 2 :(得分:2)

-r按字面意思处理输入,但是为read提供参数会导致根据IFS拆分行,其副作用是删除默认值领先和尾随空白。正如Tom Fenech指出的那样,bash read可以省略一个参数,未分割的输出存储在REPLY中。如果您不想使用REPLY,只需将IFS设置为空字符串即可防止分词。

# all uppercase variable names are reserved for the shell;
# put at least one lowercase letter or number in your names
while IFS= read -r phrase; do
    echo "$phrase"
done < phrase_file 
相关问题