【发布时间】:2011-08-13 17:13:27
【问题描述】:
我有一个由数字组成的文件。通常,每一行都包含一个数字。我想计算文件中以数字“0”开头的行数。如果是这样的话,那我想做一些后期处理。
虽然我能够正确检索相应的行号,但检索到的总行数不正确。下面,我发布我正在使用的代码。
linesToRemove=$(awk '/^0/ { print NR; }' ${inputFile});
# linesToRemove=$(grep -n "^0" ${inputFile} | cut -d":" -f1);
linesNr=${#linesToRemove} # <- here, the error
# linesNr=${#linesToRemove[@]} # <- here, the error
if [ "${linesNr}" -gt "0" ]; then
# do something here, e.g. remove corresponding lines.
awk -v n=$linesToRemove 'NR == n {next} {print}' ${anotherFile} > ${outputFile}
fi
另外,对于基于 awk 的命令,我如何使用 shell 变量?我尝试了下面的命令,但它不能正常工作,因为 'myIndex' 被解释为文本而不是变量。
linesToRemove=$(awk -v myIndex="$myIndex" '/^myIndex/ { print NR;}' ${inputFile});
鉴于在${inputFile} 中找到以0 开头的行号,我想从${anotherFile} 中删除相应的行号。下面给出了 ${inputFile} 和 ${anotherFile} 的示例:
// ${inputFile}
0
1
3
0
// ${anotherFile}
2.617300e+01 5.886700e+01 -1.894697e-01 1.251225e+02
5.707397e+01 2.214040e+02 8.607959e-02 1.229114e+02
1.725900e+01 1.734360e+02 -1.298053e-01 1.250318e+02
2.177940e+01 1.249531e+02 1.538853e-01 1.527150e+02
// ${outputFile}
5.707397e+01 2.214040e+02 8.607959e-02 1.229114e+02
1.725900e+01 1.734360e+02 -1.298053e-01 1.250318e+02
在上面的示例中,我需要从${anotherFile} 中删除行0 和3,因为这些行对应于${inputFile} 中以0 开头的行。
【问题讨论】: