【问题标题】:find and replace in in file or string in bash在bash中的文件或字符串中查找和替换
【发布时间】:2016-07-08 16:18:43
【问题描述】:

我有这个文件httpd.conf,我想找到EnableSendfile,而不是包含该字符串的行,但该行以“#”开头(不是注释行)如果找到我想重置它值关闭。

我试图想出这个。 (我是 bash 语言的新手) 但它不起作用。

我想在我的搜索和替换命令中使用变量,因为稍后我将使用数组项来循环键及其值,因此我需要使用变量而不是纯字符串。

提前感谢您的帮助!

#!/bin/bash
SEARCH="EnableSendfile"
FILEPATH="/root/scripts/httpd.conf"
REPLACE="off"

if grep -Fq $SEARCH $FILEPATH
then
    line_string=`sed -n '/^EnableSendfile/p' $FILEPATH`
    result_string="${line_string/(^[^#]\w*)(?:\s(\w+))?$/$REPLACE}"
    echo $result_string
else
    echo "not found" 
fi
#
# EnableMMAP and EnableSendfile: On systems that support it, 
# memory-mapping or the sendfile syscall may be used to deliver
# files.  This usually improves server performance, but must
# be turned off when serving from networked-mounted 
# filesystems or if support for these functions is otherwise
# broken on your system.
# Defaults if commented: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
EnableSendfile on
#EnableSendfile on

# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
IncludeOptional conf.d/*.conf

【问题讨论】:

    标签: bash replace find


    【解决方案1】:

    使用sed:

    sed 's/^EnableSendfile on/EnableSendfile off/'
    

    ^ 特殊字符匹配行首,因此该命令不会更改以 # 开头的行。

    【讨论】:

    • 我如何在 sed 中使用变量,sinc 我稍后将使用数组项来循环键及其值,因此我需要使用变量而不是纯字符串
    • 如果变量从不包含特殊字符,您可以在双引号中使用它们:"s/^$keyword on/$keyword off/"。否则,您需要更复杂的解决方案。
    • ok .i 能够做到,但显然它没有保存它只是在屏幕上显示文件,如何保存它或用它替换原始文件?
    • @Vagho:使用重定向> output,或者,如果您的 sed 版本支持它,请使用 -i 选项。
    • 我使用了它的 -i 选项,但即使它给了我这个错误 grep: on: No such file or directory