将内容替换为Linux中其他文件的内容

时间:2012-01-23 03:03:48

标签: linux unix

我的文件有一些文字(8/9行),名为abc.txt

我尝试将pqr.xml中名为 的字符串替换为上面abc.txt文件中的内容。

任何人都可以告诉我该怎么做吗?

我正在尝试使用以下命令:

sed -i~ "s/ < /Server>/HERE HOW TO PASTE CONTENTS FROM abc.txt/g" pqr.xml

3 个答案:

答案 0 :(得分:3)

我不确定sed但是awk你可能会得到你想要达到的目标。

awk脚本:

#!/usr/bin/awk -f

{
# Loop thru each words in your file

    for (i=1;i<=NF;i++) 

# When the word is pqr.xml, we read your second file

        if($i~/pqr\.xml/) 
            {
                system("cat file2"); 

# We store the content of the file in a variable and print it

                getline a; 
                printf a; 

# For everything else we just print the word as is

            }else 
                printf $i" ";
                print "";
}

File1中:

[jaypal:~/Temp] cat file
this is my pqr.xml
i want to replace

文件2:

[jaypal:~/Temp] cat file2
replacement
stuff
from
another
file

测试:

[jaypal:~/Temp] ./script.awk file
this is my replacement
stuff
from
another
file
i want to replace

答案 1 :(得分:0)

可能会比你想要的代码多一点,但是我会用perl来做这件事。如果这对你有用,请告诉我:

#!/usr/bin/perl
use warnings;
use strict;

my $xmlfile;
my $replacement;

open REPLACEMENT,"<abc.txt" or die "Couldn't open abc.txt: $!";
while (<REPLACEMENT>) { $replacement .= $_ }
close REPLACEMENT;

open XML,"<pqr.xml"  or die "Couldn't open pqr.xml: $!";
while (<IN>) { $xmlfile .= $_ }
close XML;

$xmlfile = s/< \/Server>/$replacement/gxm;

open NEW,">NEW_pqr.xml";
print NEW $xmlfile;
close NEW;

如果您需要经常这样做,请将其粘贴到名为replace.pl的文件中,例如,并将其放在与您要修改的文件相同的目录中。然后chmod it + x。然后你可以从shell脚本中调用它

答案 2 :(得分:0)

$ sed '\| < /Server>|{ r abc.txt
d; }' pqr.xml

将替换包含“&lt; / Server&gt;”的任何行与abc.txt的内容。使用sed更换部分行更加困难。