[英]How do I concatenate each line of 2 variables in bash?
I have 2 variables, NUMS
and TITLES
.我有 2 个变量,
NUMS
和TITLES
。
NUMS
contains the string NUMS
包含字符串
1
2
3
TITLES
contains the string TITLES
包含字符串
A
B
C
How do I get output that looks like:如何获得 output 看起来像:
1 A
2 B
3 C
paste -d' ' <(echo "$NUMS") <(echo "$TITLES")
Having multi-line strings in variables suggests that you are probably doing something wrong.变量中有多行字符串表明您可能做错了什么。 But you can try
但是你可以试试
paste -d ' ' <(echo "$nums") - <<<"$titles"
The basic syntax of paste
is to read two or more file names; paste
的基本语法是读取两个或多个文件名; you can use a command substitution to replace a file anywhere, and you can use a here string or other redirection to receive one of the "files" on standard input (where the file name is then conventionally replaced with the pseudo-file -
).您可以使用命令替换在任何地方替换文件,并且可以使用此处的字符串或其他重定向来接收标准输入上的“文件”之一(然后文件名通常会替换为伪文件
-
)。
The default column separator from paste
is a tab; paste
的默认列分隔符是制表符; you can replace it with a space or some other character with the -d
option.您可以使用
-d
选项将其替换为空格或其他字符。
You should avoid upper case for your private variables;您应该避免使用大写的私有变量; see also Correct Bash and shell script variable capitalization
另请参阅正确的 Bash 和 shell 脚本变量大写
Bash variables can contain even very long strings, but this is often clumsy and inefficient compared to reading straight from a file or pipeline. Bash 变量甚至可以包含很长的字符串,但与直接从文件或管道读取相比,这通常是笨拙且低效的。
Convert them to arrays, like this:将它们转换为 arrays,如下所示:
NUMS=($NUMS)
TITLES=($TITLES)
Then loop over indexes of whatever array, lets say NUMS like this:然后遍历任何数组的索引,让我们说像这样的 NUMS:
for i in ${!NUMS[*]}; {
# and echo desired output
echo "${NUMS[$i]} ${TITLES[$i]}"
}
Awk alternative: Awk 替代品:
awk 'FNR==NR { map[FNR]=$0;next } { print map[FNR]" "$0} ' <(echo "$NUMS") <(echo "$TITLE")
For the first file/variable (NR==FNR), set up an array called map with the file number record as the index and the line as the value.对于第一个文件/变量(NR==FNR),设置一个名为 map 的数组,其中文件号记录作为索引,行作为值。 Then for the second file, print the entry in the array as well as the line separated by a space.
然后对于第二个文件,打印数组中的条目以及用空格分隔的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.