在 bash 中连接字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8108232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Concatenating strings in bash
提问by Jason
A program has the output set to 2 decimal place floats, one on each line in the file. Depending on the execution, many files can be output, each with the filename cancer.ex#, where # is the number of times the program was executed from a script.
程序将输出设置为 2 个小数位浮点数,文件中的每一行一个。根据执行情况,可以输出许多文件,每个文件的文件名是cancer.ex#,其中# 是从脚本中执行程序的次数。
The professor has provided an awk script as the first step to generating a 95% confidence chart using gnuplot. I'd like to convert the output to to the format
教授提供了一个 awk 脚本,作为使用 gnuplot 生成 95% 置信度图表的第一步。我想将输出转换为格式
conf $1 $2 $3 var#
conf $1 $2 $3 var#
where # is the number from cancer.ex#
其中#是来自cancer.ex的数字#
I've developed the following:
我开发了以下内容:
#!/bin/bash
Files=Output/*
String
for f in $Files
do
String="conf "
cat $f | while read LINE
do
String="$LINE "
done
echo $String
done
I know a number of steps are missing, as I've just started putting this together. My problem is executing the concatenation part, as it simply doesn't work. There is no output, nada when executing the script above. However, if I change String="$LINEto echo $LINE, then I get all the output of the files put on the terminal.
我知道缺少许多步骤,因为我刚刚开始将它们放在一起。我的问题是执行串联部分,因为它根本不起作用。执行上面的脚本时没有输出,nada。但是,如果我更改String="$LINE为echo $LINE,那么我将获得放在终端上的所有文件输出。
Is there a workable appending function for variables inside a loop in bash?
bash 中的循环内是否有一个可行的变量附加函数?
回答by sehe
#!/bin/bash
Files=( Output/* )
String
for f in "${Files[@]}"
do
String="conf "
while read LINE
do
String+="$LINE "
done < "$f"
echo $String
done
The subtle difference with < "$f"instead of piping cat $fis mainly, that the while loop would execute in a subshell due the pipe, and the variable in the for loop would not actually be updated because of the subshell.
与< "$f"代替管道的细微差别cat $f主要是,由于管道,while 循环将在子外壳中执行,而 for 循环中的变量实际上不会因为子外壳而被更新。
Note also, how, at various points I made the filename handling more robust (accepting filenames with spaces, e.g.)
还要注意,在不同的点上,我如何使文件名处理更加健壮(例如接受带空格的文件名)
Out of the box?
盒子外面?
That all said, I suspect you might be done with simply
说了这么多,我怀疑你可能已经完成了
String="conf $(cat Output/*)"
#
String="$(for a in Output/*; do echo "conf $(cat "$a")"; done)"
Proof of concept with dummy data:
使用虚拟数据进行概念验证:
mkdir Dummy
for a in {a..f}; do for b in {1..3}; do echo $a $b; done > Dummy/$a; done
for a in Dummy/*; do echo "conf " $(cat $a); done
Output
输出
conf a 1 a 2 a 3
conf b 1 b 2 b 3
conf c 1 c 2 c 3
conf d 1 d 2 d 3
conf e 1 e 2 e 3
conf f 1 f 2 f 3

