逐行读取文件并删除后删除

时间:2018-02-01 17:42:16

标签: bash shell sed

我希望逐行阅读connectedclients.now,在阅读每个内容时执行某些操作,并在完成工作时删除该行。

实际尝试过:

ClientWork.sh:

unset n
while read -r user work codename; do
  echo $user $work $codename
  : $[n++]
done <connectedclients.now
sed "1 $n d" connectedclients.now

来自stackexchange

的原始代码

sed: -e expression #1, char 5: unexpected,&#39;`作为一个问题。有什么想法来解决它吗?

2 个答案:

答案 0 :(得分:0)

你的算术错误:$[n++],而是尝试:

((n++))

检查http://mywiki.wooledge.org/ArithmeticExpression

如果你想逐行删除:

n=0
while read -r user work codename; do
    echo "$user $work $codename"
    ((n++))
    sed -i "$n d" connectedclients.now
done < connectedclients.now

答案 1 :(得分:0)

如果你真的需要在处理每一行时删除行,我首先阅读整个文件:

file=connectedclients.now
echo "before processing, $(wc -l < "$file") lines"

mapfile -t all_lines < "$file"
for line in "${all_lines[@]}"; do
    read -r user work codename <<<"$line"
    echo $user $work $codename
    sed -i 1d "$file"
done

echo "after processing, $(wc -l < "$file") lines"