bash 从文件读取时如何保留反斜杠?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7327985/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:43:19  来源:igfitidea点击:

How to keep backslash when reading from a file?

bash

提问by paler

When I use "cat test.file", it will show

当我使用“cat test.file”时,它会显示

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

When I use the bash file,

当我使用 bash 文件时,

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

It will show

它会显示

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

The "\" is gone.

“\”不见了。

Is there any way that I can keep the "\" and space at the same time?

有什么办法可以同时保留“\”和空格?

回答by Lynch

Try using read -r.

尝试使用read -r.

From the man page:

从手册页:

-r
If this option is given, backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not be used as a line continuation.

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

Execute this to test it:

执行这个来测试它:

read -r a < <(echo "test \n test"); echo $a

回答by Satyajit

data="$(cat < test.file)"
for line in $data
do
echo "$line"
done

回答by jedwards

#!/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"

Pretty much where you were headed with the IFS plus Keith Thompson's suggestion.

IFS 和 Keith Thompson 的建议与您的目标差不多。