使用换行符将文件内容转换为 unix 变量 [英] File content into unix variable with newlines

查看:19
本文介绍了使用换行符将文件内容转换为 unix 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下内容的文本文件 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?

推荐答案

该赋值不是删除换行符,实际上是 echo 这样做了.您只需在字符串周围加上引号即可维护这些换行符:

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"

这将给出您想要的结果.有关演示,请参阅以下成绩单:

This will 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


将换行符替换为空格的原因并不完全echo 命令有关,而是多种因素的组合.


The reason why newlines are replaced with spaces is not entirely to do with the echo command, rather it's a combination of things.

当给定一个命令行时,bash 根据 IFS 变量的文档将其拆分为单词:

When given a command line, bash splits it into words according to the documentation for the IFS variable:

IFS:扩展后用于分词的Internal Field Separator ...默认值为.

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.

将它与 echo 文档(一个 bash 内部命令)结合起来,你就会明白为什么会输出空格:

Combine that with the echo documentation (a bash internal command), and you'll see why the spaces are output:

echo [-neE] [arg ...]: 输出参数,以空格分隔,后跟换行符.

echo [-neE] [arg ...]: Output the args, separated by spaces, followed by a newline.

当您使用 echo "$x" 时,它会根据 强制将整个 x 变量设为 单个 单词bash,因此它不会被拆分.你可以看到:

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

这里,count 函数只是打印出给定参数的数量.1 2 3a 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 变量的两个变体.一个没有引号表示有四个字,"test""1""test"2".添加引号使其一个单个单词"test 1 test 2".

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 test 2".

这篇关于使用换行符将文件内容转换为 unix 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆