sed将file2内容替换为file1中的file3内容

时间:2017-10-30 21:19:10

标签: bash shell awk sed

H 要搜索file1中的file2内容并使用sed将它们替换为file3内容?

file1“multiline”

    <Person><Name>Zack</Name>
        <PersonData>...</PersonData>
    </Person>

file2“multiline”

    <Employee><Name>Zack</Name>
        <EmployeeData>...</EmployeeData>
    </Employee>

file3“multiline”

sed -i -r -e '1h;2,$H;$!d;g' -e "/PLACEHOLDER/ r $2" -e "s/PLACEHOLDER// $3" $1

我正在尝试用员工替换每个Zack人员。 我试过简单的

<DB>
    <Employee><Name>Zack</Name>
        <EmployeeData>...</EmployeeData>
    </Employee>
    <Person><Name>Dave</Name>
        <PersonData>...</PersonData>
    </Person>
    <Person><Name>Lisa</Name>
        <PersonData>...</PersonData>
    </Person>
    <Employee><Name>Zack</Name>
        <EmployeeData>...</EmployeeData>
    </Employee>
</DB>

更多没有任何成功的sed操作,以便将file1更改为:

$args = array('post_type'=>'event','meta_query' => array(
    array(
        'key' => 'my_post_multicheckbox', 
         // The right value should be my_post_multicheckbox[0] 
         // and it's serialized
        'value' => serialize($current_post_ID)
    )
));
$events = new WP_Query($args);
while ($events->have_posts()):$events->the_post(); 
the_title();
endwhile;
wp_reset_query();

编辑#1:员工xml标签与人员标签完全不同 编辑#2:我没有解析xml,我试图仅通过sed或awk替换出现的事件。

2 个答案:

答案 0 :(得分:1)

这可能适合你(GNU sed):

sed -z 's/\n/\\n/g;1s/.*/s#&#/;2s/.*/&#g/' file2 file3 | sed -z -f - file1

从匹配和替换文件创建替换命令(首先引用所有换行符)。然后对源文件应用命令。

答案 1 :(得分:0)

还要考虑这个bash解决方案:

$ cat file2
Name:John Due 
Gender:Male 
Age:21
Address: Texas

Name:Ed Mundo 
Gender:Male 
Age:41 
Address: California

$ cat file22
Name:Ed Mundo 
Gender:Male 
Age:41 
Address: California

$ cat file222
SurName:Ed Mundo 
Gender:Male 
Age:61 
Address: Chicago

$ a="$(<file22)";b="$(<file222)";c="$(<file2)"

$ echo "${c//$a/$b}"
Name:John Due 
Gender:Male 
Age:21
Address: Texas

SurName:Ed Mundo 
Gender:Male 
Age:61 
Address: Chicago