用多行文本替换单行

时间:2012-03-06 00:01:50

标签: linux shell

在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

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

使用ca命令而不是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
相关问题