开发者

How to keep backslash when reading from a file?

Whe开发者_如何学Pythonn I use "cat test.file", it will show

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

When I use the bash file,

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?


Try using 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.

Execute this to test it:

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


Preserve whitespace and backslashes: IFS=, read -r and printf '%s\n' "input"

Test input: test.xml:

<test>
  <path>\\this\is\a\path.txt</path>
</test>
cat test.xml | while IFS= read -r f; do
  printf '%s\n' "$f" 
done

Outputs:

<test>
  <path>\\this\is\a\path.txt</path>
</test>


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜