在Linux中,我可以使用什么命令来用新的多行代替单行文本? 我想在一行中查找一个关键字并删除这一行,并用多个新行replace它。 因此,在下面显示的文本中,我想要search包含“关键字”的行,并用如图所示的3行新文本replace整行。
例如,replace包含关键字的行,
This is Line 1 This is Line 2 that has keyword This is Line 3
改为:
This is Line 1 Inserted is new first line Inserted is new second line Inserted is new third line This is Line 3
$ sed '/keyword/c\ > Inserted is new first line\ > Inserted is new second line\ > Inserted is new third line' input.txt This is Line 1 Inserted is new first line Inserted is new second line Inserted is new third line This is Line 3
$
和>
是bash提示符
创建一个文件script.sed
,其中包含:
/keyword/{i\ Inserted is new first line\ Inserted is new second line\ Inserted is new third line d }
将其应用于您的数据:
sed -f script.sed your_data
如何做到这一点,使用c
和a
命令,而不是i
和/或d
,但是这是相当干净的。 它找到关键字,插入三行数据,然后删除包含关键字的行。 ( c
命令完成了这一切,但我不记得它存在,并且a
命令附加了文本,并且在本文中与i
基本上是同义词。)
你也可以使用shell buildins来完成它:
STRING1_WITH_MULTIPLE_LINES="your text here" STRING2_WITH_MULTIPLE_LINES="more text" OUTPUT="" while read LINE || [ "$LINE" ]; do case "$LINE" in "Entire line matches this")OUTPUT="$OUTPUT$STRING1_WITH_MULTIPLE_LINES ";; *"line matches this with extra before and/or after"*)OUTPUT="$OUTPUT$STRING2_WITH_MULTIPLE_LINES ";; *)OUTPUT="$OUTPUT$LINE ";; esac done < file echo "$OUTPUT" >file