替换文件内容以数字开头)并保留其余行内容

时间:2019-04-03 05:12:39

标签: sed

我想用sed或类似的解决方案替换包含特殊模式的文件。我可以用单个sed替换文件,但是number可以是任何东西,需要按原样保留前缀。

实际文件:

1) L0 | Delete multiple contacts | C543072
2) L1 | Move Multiple Messages via Header toolbar Move button | C1832588
3) L1 | Move Multiple Messages contains file attachment | C2058412
- L1 | Forward message containing attachment | C1976614
- L0 | Normal message contains file attachment | PREAPPS-1488
- L3 | Forward as signed in message view | C1990347

期望的文件:

FAILED - L0 | Delete multiple contacts | C543072
FAILED - L1 | Move Multiple Messages via Header toolbar Move button | C1832588
FAILED - L1 | Move Multiple Messages contains file attachment | C2058412
SKIPPED - L1 | Forward message containing attachment | C1976614
SKIPPED - L0 | Normal message contains file attachment | PREAPPS-1488
SKIPPED - L3 | Forward as signed in message view | C1990347

尝试输入的代码:

sed -i 's/- L/SKIPPED - L/' /report.txt
sed -i 's/1) L0/FAILED - L0/' /report.txt
sed -i 's/[0-9]) L/FAILED - L[0-9]/' /report.txt (doesn't preserve LX)

是否有任何一个使用正则表达式来替换内容的命令,以及保留LX(字符串以数字(L)开头的数字)?[p]?

1 个答案:

答案 0 :(得分:2)

sed脚本中的多个命令可以用分号(;)分隔。

$ sed 's/^[0-9]\+)/FAILED -/; s/^-/SKIPPED -/' file
FAILED - L0 | Delete multiple contacts | C543072
FAILED - L1 | Move Multiple Messages via Header toolbar Move button | C1832588
FAILED - L1 | Move Multiple Messages contains file attachment | C2058412
SKIPPED - L1 | Forward message containing attachment | C1976614
SKIPPED - L0 | Normal message contains file attachment | PREAPPS-1488
SKIPPED - L3 | Forward as signed in message view | C1990347
  • ^匹配输入行的开头,
  • [0-9]\+匹配一个或多个数字。