简体   繁体   English

使用sed修改Apache端口文件

[英]Using sed to modify Apache ports file

I am trying to edit Listen 80 in ports.conf file with sed. 我正在尝试使用sed在ports.conf文件中编辑Listen 80

Since that file looks like : 由于该文件看起来像:

Listen 80

<IfModule ssl_module>
    Listen 443
</IfModule>

<IfModule mod_gnutls.c>
    Listen 443
</IfModule>

with this command: head -n1 sed_test | 使用此命令:head -n1 sed_test | sed -i -e 's/Listen [0-9]+/Listen 80/1p' sed_test sed -i -e's / Listen [0-9] + / Listen 80 / 1p'sed_test

It changes all 'Listen $port_number' in the file. 它将更改文件中的所有“ Listen $ port_number”。 I guess it is because in second command I specify a file. 我猜是因为在第二个命令中我指定了一个文件。

If I don't specify, to which file it should write, I get an error sed: no input files which is logical although. 如果未指定应写入哪个文件,则会出现错误sed: no input files尽管sed: no input files逻辑sed: no input files

I know that it can be done only with a sed, but I am unsure how to edit only one line and replace it with my custom value. 我知道只能用sed来完成,但是我不确定如何只编辑一行并将其替换为我的自定义值。

So this is what I want to accomplish: 这就是我要完成的工作:

sed -i -e some_command/Listen 8080 file sed -i -e some_command /听8080文件

cat file -> 猫文件 ->

 Listen 8080

    <IfModule ssl_module>
        Listen 443
    </IfModule>

    <IfModule mod_gnutls.c>
        Listen 443
    </IfModule>

How to do that? 怎么做?

If you are using gnu sed you can use: 如果您使用的是gnu sed ,则可以使用:

sed -i '0,/Listen [0-9]*/s//Listen 8080/' file

Listen 8080

<IfModule ssl_module>
    Listen 443
</IfModule>

<IfModule mod_gnutls.c>
    Listen 443
</IfModule>

If you don't have gnu sed then you can use awk to replace only first instance: 如果您没有使用gnu sed则可以使用awk仅替换第一个实例:

awk '!p{ p=sub(/Listen [0-9]*/, "Listen 8080") } 1' file

Listen 8080

<IfModule ssl_module>
    Listen 443
</IfModule>

<IfModule mod_gnutls.c>
    Listen 443
</IfModule>

可以通过标准sed来完成:

sed '/Listen/{s/\([0-9]\+\)/8080/; :a;n; ba}' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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