如何在Bash中编写单行命令合并多文件中Mary的汇总统计结果
Here's a single Bash command that combines Mary's summary statistics from multiple files into your desired report format:
input1_output=$(awk '/Mary/{for(n=3;n<=NF;n++) print $n}' input1.txt | Rscript -e 'summary(as.numeric(readLines("stdin")))'); echo "$input1_output"; awk '/Mary/{for(n=3;n<=NF;n++) print $n}' input2.txt | Rscript -e 'summary(as.numeric(readLines("stdin")))' | tail -n1
How it works:
- Capture Input1's full summary: We run your existing command for
input1.txtand store the entire output (header + stats line) in a variableinput1_output. This avoids reprocessinginput1.txttwice. - Print Input1's summary: Echo the stored variable to output the header and the first stats line.
- Process Input2's stats: Run the same command for
input2.txt, but usetail -n1to only capture the second line (the stats values, skipping the duplicate header), then print it.
If you have more than two files (e.g., input3.txt, input4.txt), you can extend this with a loop to avoid repeating the command for each file:
header=$(awk '/Mary/{for(n=3;n<=NF;n++) print $n}' input1.txt | Rscript -e 'summary(as.numeric(readLines("stdin")))' | head -n1); echo "$header"; for f in input1.txt input2.txt input3.txt; do awk '/Mary/{for(n=3;n<=NF;n++) print $n}' "$f" | Rscript -e 'summary(as.numeric(readLines("stdin")))' | tail -n1; done
This approach ensures the header is only printed once, followed by the summary stats line for each file containing Mary's data.
内容的提问来源于stack exchange,提问作者LockhartTech
相关产品推荐
相关产品推荐

