【问题标题】:How to cat multi-line bash variables?如何 cat 多行 bash 变量?
【发布时间】:2021-10-02 22:50:06
【问题描述】:

当我尝试保存 bash 变量列,然后尝试将它们组合在一起时,我收到了错误。

这些是变量:

$ a_var=$(grep -i "word" {input} | awk '{print $3}')

$ echo $a_var
hello1
hello2
hello3

$ b_var=$(grep -i "otherword" {input} | awk '{print $3}')

$ echo $b_var
hello10
hello11
hello12

但是当我尝试时:

$ new_var=$(cat $a $b)

我得到一些无法保存到文件或新变量的奇怪输出。

cat: hello1: No such file or directory
cat: hello2: No such file or directory
cat: hello3: No such file or directory
cat: hello10: No such file or directory
cat: hello11: No such file or directory
cat: hello12: No such file or directory

$ echo $new_var

$

(当我“回显”时,返回空白。)

发生了什么事?如何将我的 bash 变量连接在一起?

编辑:我希望输出看起来像这样(我想将此列值保存到文件中):

hello1
hello2
hello3
hello10
hello11
hello12

【问题讨论】:

  • 使用printf '%s\n' "$a" "$b"
  • 也许:new_var="$(cat $a $b)"
  • @anita :你为什么提到数组?您的示例中没有数组。
  • 你想要哪个输出?
  • @anubhava 的回答为我做了。谢谢!

标签: bash variables unix cat


【解决方案1】:

虽然cat 在 Linux 中代表连接,但它不会作用于变量。实际上,它用于连接文件并打印到标准输出设备。对于您的情况,请使用c_var="${a_var}${b_var}"

【讨论】:

  • 感谢您提供有用的解释。我更改了我的问题以表明我希望在每个条目后保留换行符以保持列格式。当我回显“${a_var}${b_var}”时,第一个和第二个变量之间没有换行符
【解决方案2】:

这是在 shell 中连接这些字符串变量的方式:

c_var="$a_var$b_var" ;回声 $c_var

或者一般来说: c="$a$b" ;回声$c

【讨论】:

    猜你喜欢
    • 2021-06-22
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 2019-01-22
    • 2011-01-30
    • 2012-06-12
    相关资源
    最近更新 更多