如何将源文件中的一些模式替换到目标文件中,包括源文件中的那些模式?

2o7dmzc5  于 2022-10-23  发布在  Linux
关注(0)|答案(4)|浏览(163)

假设源文件为源文件,目标文件为目标文件,下面使用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.

`

f2uvfpb9

f2uvfpb91#

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命令将无法正常工作。

vcudknz3

vcudknz32#

使用GNU sed

$ sed -e "/^common code starts/{e sed -n '/^common code starts/,/}/p' source_library.txt" -e 'd};/^$/,/}/d' 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.
neskvpey

neskvpey3#

如果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
jv4diomz

jv4diomz4#

cat source_library.txt | sed '/START method library function/,/END method library function/{d;r /dev/stdin}' target_file.txt
正如我们在这个问题中所讨论的,您可以使用r /dev/stdin来确保r正在读取替换部分第一行之后的空流。

相关问题