我想在 linux 处的文件中添加一些行

I Want add some line in a file at linux

我有一个 linux centos 7 服务器,我希望下面的行使用名称 config.xml

进行归档
<vhostMap>
  <vhost>google</vhost>
  <domain>google.com, www.google.com</domain>
</vhostMap>

我想在 config.xml 文件

的第 8 行之后添加此行

如何使用 sed 或 awk 命令?它的 python 还是 perl? 我搜索了很多,但对我这个菜鸟来说很难,有人能告诉我一些例子吗?

谢谢。

在Python中很容易:

to_add = """<vhostMap>
  <vhost>google</vhost>
  <domain>google.com, www.google.com</domain>
</vhostMap>
"""
with open("config.xml", "r") as f:
    all_lines = f.readlines()
with open("config.xml", "w") as f:
    for l in all_lines[:8]: f.write(l)
    f.write(to_add)
    for l in all_lines[8:]: f.write(l)

我使用 shell 命令最简单的方法是显示原始 config.xml 的前 8 行并将输出偏离到一个新文件。然后在新文件中附加您的代码,最后包括从第 8 行

开始的 config.xml 的尾部
$ head -n 8 config.xml > newconfig.xml
$ cat your_code.txt >> newconfig.xml
$ tail -n+8 config.xml >> newconfig.xml

终于可以用新文件替换原来的config.xml了。做之前检查一下config.xml的内容!

$ mv newconfig.xml config.xml

在 perl 中可以通过多种方式轻松实现此类操作,请随意选择您认为合适的一种

替代方法

use strict;
use warnings;
use feature 'say';

my $filename = 'config.xml';

my $insert = 
'<vhostMap>
  <vhost>google</vhost>
  <domain>google.com, www.google.com</domain>
</vhostMap>';

open my $fh, '<', $filename
    or die "Couldn't open $filename: $!";

my $data = do{ local $/; <$fh> };

close $fh;

$data =~ s/((.*?\n){8})/$insert\n/s;

open $fh, '>', $filename
    or die "Couldn't open $filename: $!";

say $fh $data;

close $fh;

数组切片方法

use strict;
use warnings;
use feature 'say';

my $filename = 'config.xml';

my $insert = '<vhostMap>
  <vhost>google</vhost>
  <domain>google.com, www.google.com</domain>
</vhostMap>';

open my $fh, '<', $filename
    or die "Couldn't open $filename: $!";

my @lines = <$fh>;

close $fh;

open $fh, '>', $filename
    or die "Couldn't open $filename: $!";

say $fh @lines[0..7],$insert,"\n",@lines[8..$#lines];

close $fh;

数组迭代方法

use strict;
use warnings;
use feature 'say';

my $filename = 'config.xml';

my $insert = '<vhostMap>
  <vhost>google</vhost>
  <domain>google.com, www.google.com</domain>
</vhostMap>';

open my $fh, '<', $filename
    or die "Couldn't open $filename: $!";

my @lines = <$fh>;

close $fh;

open $fh, '>', $filename
    or die "Couldn't open $filename: $!";

my $line_count = 0;

for (@lines) {
    chomp;
    $line_count++;      
    say $fh $_; 
    say $fh $insert if $line_count == 8;
}

close $fh;

输入

line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10
line 11
line 12

输出

line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
<vhostMap>
  <vhost>google</vhost>
  <domain>google.com, www.google.com</domain>
</vhostMap>
line 9
line 10
line 11
line 12