如何在源文件到目标文件的某些模式之间进行替换,包括源文件中的那些模式



假设source_library.txt是源文件,target_file.txt是目标文件,我使用cat命令显示下面的文件内容

`$cat source_library.txt
// START method library function
{
common code starts...
I am the library which can be used in target files.
you can use me..
}
// END method library function
$ cat target_file.txt   (before executing that sed command)
My name is Bikram
// START method library function
{
common code starts...
}
// END method library function
Outside of this method.`

执行以下命令后输出:

sed -i '/START method library function/,/END method library function/!b;//!d;/START method library function/r source_library.txt' target_file.txt

此命令的输出:

`$cat target_file.txt (after executing that sed command)
My name is Bikram
// START method library function
// START method library function
{
common code starts...
I am the library which can be used in target files.
you can use me..
}
// END method library function
// END method library function
Outside of this method.`

但预期的输出我需要在target_file.txt中作为

`My name is Bikram
// START method library function
{
common code starts...
I am the library which can be used in target files.
you can use me..
}
// END method library function
Outside of this method.

`

这个sed命令应该完成以下工作:

sed -n -i.backup '
/START method library function/,/END method library function/!p
/START method library function/r source_library.txt
/END method library function/{x;p;}
' target_file.txt

请注意,如果有一行包含START method library function而没有相应的END method library function,则此sed命令将无法正常工作。

如果ed可用/可接受。

脚本script.ed,可以随意命名。

/START method library function/;/END method library function/;?common code starts...?;/}/-w tmp.txt
E target_file.txt
/{/;/common code/;/}/;?{?r tmp.txt
+;/^$/d
,p
Q

现在运行

ed -s source_library.txt < script.ed

使用here document,类似于。

#!/bin/sh
ed -s source_library.txt <<-'EOF'
/START method library function/;/END method library function/;?common code starts...?;/}/-w tmp.txt
E target_file.txt
/{/;/common code/;/}/;?{?r tmp.txt
+;/}/-d
,p
Q
EOF

  • 它创建了一个临时文件(名为tmp.txt的文件(,其内容来自source_library.txt

  • 如果之后不需要临时文件,请在+;/}/-d行之后添加!rm tmp.txt

  • 如果不需要输出到stdout,则移除,p

  • 如果需要就地编辑target_file.txt,请将Q更改为w

cat source_library.txt | sed '/START method library function/,/END method library function/{d;r /dev/stdin}' target_file.txt

正如我们在这个问题中所讨论的,您可以使用r /dev/stdin来确保r在替换部分的第一行之后读取空流。

相关内容

  • 没有找到相关文章

最新更新