我有一个由数字组成的文件。通常,每行包含一个单一的数字。我想要统计文件中以数字“0”开头的行数。如果是这样的话,那么我想做一些后期处理。将命令的输出分配给shell变量并获取变量大小
虽然我能够正确检索相应的行号,但检索行的总数不正确。下面,我发布我正在使用的代码。
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
在上面的例子中,我需要删除线0
和从${anotherFile}
3
,因为这些行对应于开头的行0
in ${inputFile}
。
@ ghosdog74,谢谢!实际上,最终目标是从一个文件中检索以0开头的行,然后从另一个文件中删除相应的行。此外,是否有可能使用变量'linesToRemove'的大小/长度来查找总行数? – Javier 2011-04-27 12:38:10
@Javier,你应该发布这些文件的样本,并显示你的最终输出。我可以更好地向你展示,如果不是比你现在正在做的更有效的方式 – ghostdog74 2011-04-27 12:45:58
@ ghosdog74,我更新了这篇文章,并包含了这两个文件的一些示例。 – Javier 2011-04-27 12:56:32