如何用一个简单的命令将大量变量附加到一个变量上 [英] How to append lots of variables to one variable with a simple command

查看:91
本文介绍了如何用一个简单的命令将大量变量附加到一个变量上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将所有变量都放在一个变量中

I want to stick all the variables into one variable

A=('blah')
AA=('blah2')
AAA=('blah3')
AAB=('blah4')
AAC=('blah5')
#^^lets pretend theres 100 more of these ^^
#Variable composition
#after AAA, is AAB then AAC then AAD etc etc, does that 100 times

我希望将它们全部放入此MASTER变量

I want them all placed into this MASTER variable

#MASTER=${A}${AA}${AAA} (<-- insert AAB, AAC and 100 more variables here)

我显然不想在此表达式中键入100个变量,因为可能有一种更简单的方法来执行此操作.另外,我将做更多的事情,因此我需要自动化.

I obviously don't want to type 100 variables in this expression because there's probably an easier way to do this. Plus I'm gonna be doing more of these therefore I need it automated.

我对sed比较陌生,awk,有没有办法将这100个变量附加到主变量中?

I'm relatively new to sed, awk, is there a way to append those 100 variables into the master variable?

为此,我不需要数组.

推荐答案

您可以使用简单单线,虽然很昂贵,但很简单:

You can use a simple one-liner, quite straightforward, though more expensive:

master=$(set | grep -E '^(A|AA|A[A-D][A-D])=' | sort | cut -f2- -d= | tr -d '\n')

  • set列出所有var=name格式的变量
  • grep过滤掉我们需要的变量
  • sort按正确的顺序放置它们(由于set提供排序的输出,因此可能是可选的)
  • cut提取值,删除变量名
  • tr删除换行符
    • set lists all the variables in var=name format
    • grep filters out the variables we need
    • sort puts them in the right order (probably optional since set gives a sorted output)
    • cut extracts the values, removing the variable names
    • tr removes the newlines
    • 让我们测试一下.

      A=1
      AA=2
      AAA=3
      AAB=4
      AAC=5
      AAD=6
      AAAA=99 # just to make sure we don't pick this one up
      master=$(set | grep -E '^(A|AA|A[A-D][A-D])=' | sort | cut -f2- -d= | tr -d '\n')
      echo "$master"
      

      输出:

      123456
      

      这篇关于如何用一个简单的命令将大量变量附加到一个变量上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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