2011-09-07 65 views
13

当我使用 “猫TEST.FILE”,它会显示从文件读取时如何保留反斜线?

printf "This is a test log %d \n, testid"; 
1 
    2 

当我使用bash的文件,

IFS="" 
while read data 
do 
    echo "$data" 
done << test.file 

它会显示

printf "This is a test log %d n, testid"; 
1 
    2 

的 “\”离开了。

有什么办法可以保持“\”和空格在同一时间吗?

+2

我想你的意思'

+1

'信息bash',搜索 “读” 条命令:“反斜线字符'\'可用于删除下一个字符读取和行续行的任何特殊含义。” (这不能解决问题,但它解释了它。) –

回答

24

尝试使用read -r

从手册页:

-r
如果这个选项,则反斜杠不作为转义字符 。 反斜杠被认为是该行的一部分。特别是, 反斜杠 - 换行符 对可能不能用作续行。

执行此测试它:

read -r a < <(echo "test \n test"); echo $a 
0
data="$(cat < test.file)" 
for line in $data 
do 
echo "$line" 
done 
+2

简单:'data =“$(cat test.file)”'''''data =“$(

+2

您不需要将整个文件写入'$ data'。用于$(

+0

你仍然需要玩IFS以防止bash将它们解释为分隔符。 – jedwards

0
#!/bin/bash 

# Store the original IFS 
OIFS="$IFS" 
# Update the IFS to only include newline 
IFS=$'\n' 
# Do what you gotta do... 
for line in $(<test.file) ; do 
    echo "$line" 
done 
# Reset IFS 
IFS="$OIFS" 

差不多,你正在与IFS加基思·汤普森的建议领导。

相关问题