首页 > 解决方案 > 将文件读入变量保留空格和换行符

问题描述

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

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

只是为了简单起见,假设我打算存储在变量中的输入/粘贴如下:

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 / 也如上所示

编辑 - 可能有人好奇我的实际用例是什么,所以我举一个例子,我的粘贴在实际用例中实际上是什么。为了简单起见,我使用了有问题的 1..5 示例。

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

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

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

尽管我将粘贴 300,400 对这样的行(如果重要的话)。

标签: linuxbashunixawksed

解决方案


如果这不是您所需要的全部,请发布一个新问题:

$ foo=$(< file)
$ printf '%s\n' "$foo"
1
 2
  3
   4
    5

推荐阅读