简体   繁体   中英

sed replace file2 content with file3 content in file1

H ow to search file1 for file2 contents and replace them with file3 contents using sed?

file1 "multiline"

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

file2 "multiline"

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

file3 "multiline"

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

I'm trying to replace every Zack person with an employee. I've tried from simple

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

to even more without any successful sed operation in order to change file1 to:

<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>

Edit #1: Employee xml tags are completely different from person tags.
Edit #2: I'm not parsing xml, am trying to replace occurrences only through sed or awk.

This might work for you (GNU sed):

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

Create a substitution command from the match and replacement files (first quoting all newlines). Then apply the command against the source file.

Consider also this bash solution:

$ 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM