在Linux中,我可以用什么命令用新的多行替换单行文本?我想在一行上查找关键字并删除此行并将其替换为多个新行。因此,在下面显示的文本中,我想搜索包含“keyword”的行,并用3行新文本替换整行,如图所示。
例如,替换包含关键字的行
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
答案 0 :(得分:12)
$ 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提示
答案 1 :(得分:8)
创建一个文件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
同义。)
答案 2 :(得分:1)
你也可以使用shell builtins来做到这一点:
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