我有一个包含如下数据的文件(halted.txt
IMPORT_FRP_DRAWDOWN_MQ,1
eFXO_IMPORT_RFQ_MQ,1
IMPORT_FROM_MCDM,1
deal_export,1现在的问题是如何对这个文件进行循环,并执行一些操作(在ned的数量上加+1 ),每行只执行一次,当数量为5或>5时停止
IFS=$'\n' # make newlines the only separator
set -f # disable globbing
for p in $(cat < "halted.txt"); do
if [[ $p == *"5"* ]]; then
echo "There is 5 on the end", $p
elif [[ $p > *"5"* ]]; then
echo "add +1 till 5"
awk -F, '{$2=$2+1}1' OFS=, halted.txt > temp && mv temp halted.txt
fi
done目前,每次运行的编号1不仅增加了1,而且增加了4倍,因为我在文件中有4行。那么第一次运行将会给我
IMPORT_FRP_DRAWDOWN_MQ,4
eFXO_IMPORT_RFQ_MQ,4
IMPORT_FROM_MCDM,4
deal_export,4下一个8等等。如何确保as results仅+1将被添加?
发布于 2019-02-28 15:50:22
每次从文件中读取另一行时,您都会使用Awk重写该文件。只需使用Awk一次性完成所有这些操作。
if awk -F , 'BEGIN { OFS=FS } ++$NF >= 5 { exit 1 } 1' halted.txt >halted.txt.tmp
then
mv halted.txt.tmp halted.txt
else
echo "$0: terminated with error" >&2
rm halted.txt.tmp # or maybe do this outside the if?
fi通常,您希望避免在Bash中行上循环,特别是在循环中反复处理整个文件。
如果您希望Awk完成处理,但发出失败信号,请尝试
if awk -F , 'BEGIN { OFS=FS; rc=0 } ++$NF >= 5 { rc=1 } 1; END { exit rc }' halted.txt >halted.txt.tmp
then
: nothing
else
echo "$0: we are done" >&2
fi
mv halted.txt.tmp halted.txthttps://stackoverflow.com/questions/54919692
复制相似问题