替换匹配行前面N行的内容

要求:sed 4.2.2+

https://unix.stackexchange.com/questions/206886/print-previous-line-after-a-pattern-match-using-sed

  1. cat test.txt
  2. status: done
  3. memory: 1G
  4. name: bwa_mem_S1
  5. test: hehe
  6. status: waiting
  7. memory: 1G
  8. name: bwa_mem_S2
  9. test: hehe
  10. status: waiting
  11. memory: 1G
  12. name: qc_S1
  13. test: hehe
  14. status: waiting
  15. memory: 1G
  16. name: qc_S2
  17. test: hehe
  18. cat test.txt | sed -zE 's#waiting(\n[^\n]*\nname: bwa_mem*)#done\1#g'
  • -z: 一次性读取全部文件
  • -E: 使用扩展的正则匹配模式,可以匹配换行符
  • \1: 表示子组()匹配到的第一个