文件内容与换行符UNIX变 [英] File content into unix variable with newlines
问题描述
我有以下内容的文本文件test.txt:
I have a text file test.txt with the following content:
text1
text2
和我想要的文件到UNIX变量的内容分配,但是当我这样做:
And I want to assign the content of the file to a UNIX variable, but when I do this:
testvar=$(cat test.txt)
echo $testvar
结果是:
text1 text2
而不是
text1
text2
有人建议我一个解决方案吗?
Can someone suggest me a solution for this?
推荐答案
这个分配的不的删除换行符,它实际上是在回声
这样做。你只需把引号括起来的周围,以保持这些新行:
The assignment does not remove the newline characters, it's actually the echo
doing this. You need simply put quotes around the string to maintain those newlines:
echo "$testvar"
这WIL给你想要的结果。请参见下面的成绩单为演示:
This wil give the result you want. See the following transcript for a demo:
pax> cat num1.txt ; x=$(cat num1.txt)
line 1
line 2
pax> echo $x ; echo '===' ; echo "$x"
line 1 line 2
===
line 1
line 2
的的原因的,为什么换行用空格代替不是的完全的做的回声
命令,而它的事物的组合。
The reason why newlines are replaced with spaces is not entirely to do with the echo
command, rather it's a combination of things.
在给定的命令行,庆典
根据为 IFS
变量的文件拆分成词:
When given a command line, bash
splits it into words according to the documentation for the IFS
variable:
IFS:内部字段分隔符是膨胀后用分词...默认值为<空><标签><换行符>
。
IFS: The Internal Field Separator that is used for word splitting after expansion ... the default value is
<space><tab><newline>
.
这是指定,默认情况下,所有这三个字符可用于您的命令拆分成单个的单词。在此之后,字分隔都走了,你就只剩下一个单词列表。
That specifies that, by default, any of those three characters can be used to split your command into individual words. After that, the word separators are gone, all you have left is a list of words.
再加上与回声
文档(A 庆典
内部命令),你就会明白为什么空间输出:
Combine that with the echo
documentation (a bash
internal command), and you'll see why the spaces are output:
回声[-neE] [参数...]:输出指定参数时,用空格隔开,跟着一个换行符
echo [-neE] [arg ...]: Output the args, separated by spaces, followed by a newline.
当您使用回声$ X
,它迫使整个 X
变量是一个的根据庆典
单的字,因此它不是分裂。你可以看到,有:
When you use echo "$x"
, it forces the entire x
variable to be a single word according to bash
, hence it's not split. You can see that with:
pax> function count {
...> echo $#
...> }
pax> count 1 2 3
3
pax> count a b c d
4
pax> count $x
4
pax> count "$x"
1
在这里,计数
函数简单地打印出给定参数的个数。在 1 2 3
和 A B C D
变种显示它在行动。
Here, the count
function simply prints out the number of arguments given. The 1 2 3
and a b c d
variants show it in action.
然后,我们尝试用在 X
变量中的两个变化。一的没有的报价显示,有四个字,测试
,1
,测试
和2
。添加引号使得它的有一个的单个字测试1 \\ 2 NTEST
。
Then we try it with the two variations on the x
variable. The one without quotes shows that there are four words, "test"
, "1"
, "test"
and "2"
. Adding the quotes makes it one single word "test 1\ntest 2"
.
这篇关于文件内容与换行符UNIX变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!