2016-07-08 41 views
0

我有這個文件httpd.conf,我想找到EnableSendfile,而不是包含字符串的行,但該行開始以「#」(沒有註釋行),如果發現我想將其值重置爲關閉。查找和替換在文件或字符串在bash

我試圖想出這個。 (我是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 

回答

0

使用sed

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

^特殊字符的行的開頭匹配,所以該命令將不會改變行開始用#

+0

hhow我可以使用變量與sed,sinc我打算稍後使用數組項來循環鍵和它們的值,因此我需要使用變量而不是普通字符串 – Vagho

+0

如果變量從不包含特殊字符,你可以在雙引號中使用它們:'「/關鍵字/ $關鍵字/」'。否則,你需要一個更復雜的解決方案。 – choroba

+0

好的.i能夠做到這一點,但顯然它不是保存它只是在屏幕上顯示文件,如何保存或替換原始文件? – Vagho