如何将文件的内容插入perl / shell中的另一个文件(如果是regexp)

时间:2012-02-28 05:36:59

标签: regex perl shell insert paste

File1 Contents:

line1-file1      "1" 
line2-file1      "2"
line3-file1      "3" 
line4-file1      "4" 

File2 Contents:

line1-file2     "25"  
line2-file2     "24"  
Pointer-file2   "23"  
line4-file2     "22" 
line5-file2     "21"

执行perl / shell脚本后,

File 2 content should become

line1-file2     "25"  
line2-file2     "24"  
Pointer-file2   "23" 
line1-file1      "1" 
line2-file1      "2"
line3-file1      "3" 
line4-file1      "4"  
line4-file2     "22" 
line5-file2     "21"

即在包含行的“指针”之后将文件1的内容粘贴到文件2中。

由于

2 个答案:

答案 0 :(得分:7)

使用r中的 sed 命令附加文字文件:

$ sed -i '/Pointer-file2/r file1' file2

$ cat file2
line1-file2     "25"
line2-file2     "24"
Pointer-file2   "23"
line1-file1      "1"
line2-file1      "2"
line3-file1      "3"
line4-file1      "4"
line4-file2     "22"
line5-file2     "21"

使用r中的 ed 命令插入文字文件:

$ echo -e '/Pointer/-1r file1\n%w' | ed -s file2

$ cat file2
line1-file2     "25"
line2-file2     "24"
line1-file1      "1"
line2-file1      "2"
line3-file1      "3"
line4-file1      "4"
Pointer-file2   "23"
line4-file2     "22"
line5-file2     "21"

答案 1 :(得分:4)

use Tie::File。粗略地说,

use Tie::File;
tie my @a, 'Tie::File', 'File2' or die;
tie my @b, 'Tie::File', 'File1' or die;
for (0..$#a) {
  if (/^Pointer-file2/) {
    splice @a, $_, 0, @b;
    last
  }
}

它比使用sed更长,但是也应该更容易看到你如何改变这个稍微不同的任务。