我有一个以下格式的文件:
--- V1 ---
Hi there
--- V2 ---
--- V3 ---
What's good
--- V4 ---
--- V5 ---
--- V6 ---
我想使用某种 bash 脚本来删除任何以三个破折号开头且后面没有紧接着三个破折号的行,例如:
--- V1 ---
Hi there
--- V3 ---
What's good
我可以轻松删除所有以破折号开头的行,但不知道如何根据下一行(或者,根据非虚线前面的行)来执行此操作。
答案1
grep -v -B1 "^---" file.name
将查找所有不以“---”开头的行并显示这些行。“-B1”显示紧接在前的行。
答案2
我猜“某种”的意思是,你不坚持使用纯 bash。如果是这样,那么 awk 可以做得很好:
/tmp$ input="--- V1 ---
Hi there
--- V2 ---
--- V3 ---
What's good
--- V4 ---
--- V5 ---
--- V6 ---"
/tmp$ echo "$input" | awk '/^---/ {row = $0; if (wasdashed) next; wasdashed=1; next}; { if (wasdashed) print row; print $0}'
--- V1 ---
Hi there
--- V3 ---
What's good
/tmp$
无论如何,使用同样的逻辑,纯 bash 是可能的,但需要更多的编码。