【发布时间】:2014-08-07 14:45:47
【问题描述】:
这是我想用来将 hist.txt 中的 3 列分隔为 2 个单独文件的代码,hist1.dat 包含第一列和第二列, hist2.dat 包含第一列和第三列。 hist.txt 中的列可以用多个空格分隔。我想在 histogram1.dat 和 histogram2.dat 中保存前 n 行,直到最后一个非零值。
脚本创建 histogram1.dat 正确,但 histogram2.dat 包含 hist2.dat 中的所有行。
hist.txt 就像: http://pastebin.com/JqgSKZrP
#!bin/bash
sed 's/\t/ /g' hist.txt | awk '{print $1 " " $2;}' > hist1.dat
sed 's/\t/ /g' hist.txt | awk '{print $1 " " $3;}' > hist2.dat
head -n $( awk 'BEGIN {last=1}; {if($2!=0) last=NR};END {print last}' hist1.dat) hist1.dat > histogram1.dat
head -n $( awk 'BEGIN {last=1}; {if($2!=0) last=NR};END {print last}' hist2.dat) hist2.dat > histogram2.dat
这个问题的原因是什么?可能是因为head 的一些特殊限制?
谢谢。
【问题讨论】:
-
FWIW,你的第一个 sed | awk 可以简化为
awk '{print $1, $2}' hist.txt