如何从文件定义和设置变量?

如何从文件定义和设置变量?

我有两个文件one.txt和其他two.txt.

one.txt 文件内容:

"21"
"22"
"23"

二.txt文件内容:

"Hi how are you"
"Hello who are you"
"May I help you"

现在我想提取第一行one.txt并在开头附加一个“_”(下划线)以使其成为变量,然后提取第一行two.txt并将其分配给声明的变量,即,它应该看起来像

_21="Hi how are you"
_22="Hello who are you"
_23="May i help you"
echo $_21     #This should print "Hi how are you"

该变量应按上述方式声明。是否可以使用 bash 脚本来做到这一点?

答案1

使用粘贴,就像@αГsнιη的答案,但处理更简单一些

while IFS=$'\t' read num value; do
  declare "_$num=$value"
done < <(paste {one,two}.txt)

然后

$ echo "$_21"
Hi how are you

$ echo "$_22"
Hello who are you

$ echo "$_23"
May I help you

答案2

eval "$(paste -d"_=''" /dev/null <(tr -d \" <one) /dev/null two /dev/null)"

paste-d="..."带有列表中定义的分隔符的文件/输入。

我们用作/dev/null虚拟输入,以便生成第一个文件内容_并将第二个文件two内容放在单引号内,以避免展开每个文件内容(如果它们包含变量、命令替换);就像下面的输入一样:

一.txt:

"21"
"22"
"23"

二.txt:

"Hi $(date) how are you"
"Hello who are you"
"May I help you"

输出是:

_21='"Hi $(date) how are you"'
_22='"Hello who are you"'
_23='"May I help you"'

$ echo "${_21}"
"Hi $(date) how are you"

如果您希望它们在分配给相关变量之前扩展,请将命令更改为:

$ eval "$(paste -d"_=" /dev/null <(tr -d \" <one) two )"
$ echo "${_21}"
Hi Tue 24 Nov 2020 12:47:40 AM +0330 how are you

相关内容