How to append lots of variables to one variable with a simple command

半世苍凉 提交于 2019-12-06 04:42:12

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 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

Let's test it.

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"

Output:

123456

With my best guess, how about:

#!/bin/bash

A=('blah')
AA=('blah2')
AAA=('blah3')
AAB=('blah4')
AAC=('blah5')
# to be continued ..

for varname in A AA A{A..D}{A..Z}; do
    value=${!varname}
    if [ -n "$value" ]; then
        MASTER+=$value
    fi
done

echo $MASTER

which yields:

blahblah2blah3blah4blah5...

Although I'm not sure whether this is what the OP wants.

echo {a..z}{a..z}{a..z} | tr ' ' '\n' | head -n 100 | tail -n 3
adt
adu
adv

tells us, that it would go from AAA to ADV to reach 100, or for ADY for 103.

echo A{A..D}{A..Z} | sed 's/ /}${/g'
AAA}${AAB}${AAC}${AAD}${AAE}${AAF}${AAG}${AAH}${AAI}${AAJ}${AAK}${AAL}${AAM}${AAN}${AAO}${AAP}${AAQ}${AAR}${AAS}${AAT}${AAU}${AAV}${AAW}${AAX}${AAY}${AAZ}${ABA}${ABB}${ABC}${ABD}${ABE}${ABF}${ABG}${ABH}${ABI}${ABJ}${ABK}${ABL}${ABM}${ABN}${ABO}${ABP}${ABQ}${ABR}${ABS}${ABT}${ABU}${ABV}${ABW}${ABX}${ABY}${ABZ}${ACA}${ACB}${ACC}${ACD}${ACE}${ACF}${ACG}${ACH}${ACI}${ACJ}${ACK}${ACL}${ACM}${ACN}${ACO}${ACP}${ACQ}${ACR}${ACS}${ACT}${ACU}${ACV}${ACW}${ACX}${ACY}${ACZ}${ADA}${ADB}${ADC}${ADD}${ADE}${ADF}${ADG}${ADH}${ADI}${ADJ}${ADK}${ADL}${ADM}${ADN}${ADO}${ADP}${ADQ}${ADR}${ADS}${ADT}${ADU}${ADV}${ADW}${ADX}${ADY}${ADZ

The final cosmetics is easily made by hand.

One-liner using a for loop:

for n in A AA A{A..D}{A..Z}; do str+="${!n}"; done; echo ${str}

Output:

blahblah2blah3blah4blah5

Say you have the input file inputfile.txt with arbitrary variable names and values:

name="Joe"
last="Doe"
A="blah"
AA="blah2

then do:

master=$(eval echo $(grep -o "^[^=]\+" inputfile.txt | sed 's/^/\$/;:a;N;$!ba;s/\n/$/g'))

This will concatenate the values of all variables in inputfile.txt into master variable. So you will have:

>echo $master
JoeDoeblahblah2
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!