首页 > 解决方案 > bash 将多列粘贴到同一个文件中

问题描述

我在循环中运行一个命令来生成一个包含 n 列的文件。为方便起见,让我们说 10 以使其简单。例如:

# Run the command to produce the data. Pipe the output to a temp file
${command here} > tmp1.txt

# We have a bit of superfluous information, so just pipe the output we need
tail -n +7 tmp1.txt | awk '{print $7}' > tmp2.txt

上面的命令只会生成一个包含 1 列数据的文件。

问题是,我希望这一切都包含在一个循环中运行 n 次。因此,tmp3.txt(输出)应该有 n 列。当我尝试添加以下命令时:

for i in {1..10}
do
  ${command here} > tmp1.txt
  tail -n +7 tmp1.txt | awk '{print $7}' > tmp2.txt
  if [[ ! -f tmp3.txt ]]
  then
    cp tmp2.txt tmp3.txt
  else
    paste -d' ' tmp2.txt tmp3.txt >> tmp3.txt
  fi
done

该文件爆炸了,甚至在 3 或 4 次迭代后我的内存都用完了。我将如何实现预期目标?写出 30-50 次并单独粘贴每个文件会很麻烦。

标签: bashpaste

解决方案


尝试

paste -d' ' tmp2.txt tmp3.txt > tmp4.txt  &&  mv tmp4.txt tmp3.txt

你永远不应该在同一个文件中读写。


推荐阅读