Python 我想在linux的文件中添加一些行
我有一台linux centos 7服务器,我想在下面几行中使用config.xml文件 谷歌 google.com,www.google.com 我想在config.xml文件的第8行之后添加这几行 如何使用sed或awk命令?是python还是perl? 我搜索了很多,但对我来说很难,因为我没有,有人能告诉我一些例子吗 谢谢。在Python中,它很简单:Python 我想在linux的文件中添加一些行,python,linux,perl,centos7,Python,Linux,Perl,Centos7,我有一台linux centos 7服务器,我想在下面几行中使用config.xml文件 谷歌 google.com,www.google.com 我想在config.xml文件的第8行之后添加这几行 如何使用sed或awk命令?是python还是perl? 我搜索了很多,但对我来说很难,因为我没有,有人能告诉我一些例子吗 谢谢。在Python中,它很简单: to_add = """<vhostMap> <vhost>google</vhost> &l
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
最后,您可以用newfile替换原始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})/${1}$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;
输出
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
注意,这里有一个竞争条件。如果进程在第二次打开后,在最后一次写入完成之前终止,数据可能会丢失。@Williampersell我唯一能想到的解决办法是写入一个临时文件,然后用临时文件替换原始文件,但这可能会使事情变得过于复杂。我刚刚做了这个:nano test.py并将代码粘贴到它上,然后使用python test.py运行它,然后我看到下面的输出:回溯最近的调用last:File test.py,第9行,在f.writeall_lines[:8]类型错误:需要字符缓冲区对象抱歉,我的错误。更正。@Błotosmętek是的,现在它可以工作了,谢谢,我可以问一下您为什么不使用sed或awk命令执行此操作吗?也许可以帮助您。方法
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