使用SED,如何在文件最后一行的开头添加“#”?

时间:2020-02-11 08:35:03

标签: sed

让我说我有这个文件:

##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;

    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.html index.php index.htm index.nginx-debian.html;

    server_name _;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }

    # pass PHP scripts to FastCGI server
    #
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
    #
    #   # With php-fpm (or other unix sockets):
        fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
    #   # With php-cgi (or other tcp sockets):
    #   fastcgi_pass 127.0.0.1:9000;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #   deny all;
    #}
}

如何在“}”之前的最后一行添加“#”?

我已经尝试过sudo sed '91 s/}/#}/' /etc/nginx/sites-available/default 这样做是为了向我显示屏幕上的更改,但实际上没有更改文件。

2 个答案:

答案 0 :(得分:2)

文件的最后一行的地址为$

我们可以使用^命令将行(#)的开头替换为s

综上所述,我们有一个非常简单的sed程序:

$s/^/#/

我们可以通过简单的shell命令在您的文件上执行该操作:

sed -e '$s/^/#/' -i "$file"

答案 1 :(得分:1)

就个人而言,要在脚本中就地编辑文件,相对于非POSIX标准ed,我更喜欢sed -i(另外,因为它将文件视为一个整体,并进行一行处理一次,一些更复杂的事情要容易得多)。当然,如果您不自动执行此操作,则只需使用emacsvi或您喜欢的编辑器即可。

ed -s /etc/nginx/sites-available/default <<EOF
$s/}/#}/
w
EOF