将文件读入变量保留空格和换行符 [英] Read a file into variable preserving spaces and newlines

查看:68
本文介绍了将文件读入变量保留空格和换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如问题所暗示的那样,我打算使用单个变量通过bash脚本以原始格式存储输入.

As the question implies I am intending to store the input through a bash script in raw format using a single variable.

基本上,当出现输入提示时,我将粘贴一些行,然后将存储的变量写入文本文件.经过一番搜索,我确实遇到了readarray,但是它没有以原始粘贴状态存储输入/粘贴

Basically when the input prompt occurs, I would be pasting some bunch of lines and then writing that stored variable to a text file. After a bit of search I did came across readarray but it is not storing the input/paste in its original paste state

为简单起见,我要存储在变量中的输入/粘贴如下:

Just for the purpose of simplicity lets say the input/paste I am intending to store in the variable is as follows:

1
 2
  3
   4
    5

期望的脚本

#!/bin/bash
#the part i need help with ( Store the multiple line input/paste in raw format in a variable called let say test ) 
....
echo "$test" > test.txt
cat test.txt

这应该完全按照我在控制台/输入提示中粘贴的格式打印1..5,也如上所示

This should print that 1..5 exactly in the format I have pasted during input prompt in console / also shown above

编辑-可能有人好奇我的实际用例是什么,所以我举一个例子说明我的粘贴实际在实际用例中是什么.我仅出于简单起见使用了1..5示例.

Edit - It might be possible someone is curious what is my actual use case, so I am giving an example what my paste actually is in real use case. I used 1..5 example in question only for simplicity.

https://cdn.jwplayer.com/videos/XXXizsW4-32313922.mp4
  out=Lecture 01- AS 1 Theory.mp4
https://cdn.jwplayer.com/videos/XXX6XFPB-32313922.mp4
  out=Lecture 02- AS 1 Question.mp4
https://cdn.jwplayer.com/videos/XXXIeQNM-32313922.mp4
  out=Lecture 03- AS 2 Theory.mp4

我只会以这种格式粘贴文本

I would be pasting text in such format only

https://link
  out=Some-Name.mp4 ( 2 spaces before word out )

尽管我要粘贴300,400条这样的线对(如果有关系的话).

Although there are 300,400 such pairs of lines that I would be pasting (if that matters).

推荐答案

问题显然出在如何编写变量上.如果使用数组,则在编写时需要正确引用它.

The problem is apparently with how you write the variable. If you use an array, you need to quote it correctly when you write it.

readarray -d $'\n' test
printf '%s\n' "${test[@]}"

也许还请参见何时将引号括在shell变量周围?

这篇关于将文件读入变量保留空格和换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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