在文件中查找文本

时间:2018-06-07 18:03:25

标签: shell unix echo vi

这是我想要实现的,似乎它有一些错误。转义字符串中的序列尚未添加

search_string="LoadModule rewrite_module "${ORACLE_HOME}/ohs/modules/mod_rewrite.so"
insert_string1="LoadModule reqtimeout_module "${ORACLE_HOME}/modules/mod_reqtimeout.so"
insert_string2="<IfModule reqtimeout_module>RequestReadTimeout header=20-40,MinRate=500 body=20,MinRate=500 </IfModule>"
grep "$insert_string1" httpds.conf;
if [ $? -ne 0 ]; then
    sed -r -e ":a;/${search_string}/ {n;s/$/${insert_string1}/};ta" httpds.conf
    sed -r -e ":a;/${insert_string1}/ {n;s/$/${insert_string2}/};ta" httpds.conf
    echo "Configuration inserted successfully"
fi
####################输出文件应如下所示
LoadModule unique_id_module "${ORACLE_HOME}/ohs/modules/mod_unique_id.so"
LoadModule setenvif_module "${ORACLE_HOME}/ohs/modules/mod_setenvif.so"
LoadModule context_module "${ORACLE_HOME}/ohs/modules/mod_context.so"
LoadModule rewrite_module "${ORACLE_HOME}/ohs/modules/mod_rewrite.so"
LoadModule reqtimeout_module "${ORACLE_HOME}/modules/mod_reqtimeout.so"
<IfModule reqtimeout_module>
   RequestReadTimeout header=20-40,MinRate=500 body=20,MinRate=500 
</IfModule>"

LoadModule dumpio_module "${ORACLE_HOME}/ohs/modules/mod_dumpio.so"

3 个答案:

答案 0 :(得分:0)

您可以使用sed

查看此内容

sed -i '/string/a SampleInsert/' configfile.txt

如果不支持-i,那么只需将输出重定向到新文件:

sed '/string/a SampleInsert/' configfile.txt > output_file.txt

答案 1 :(得分:0)

通过追加你的意思是添加到匹配线后面的行尾?如果是这样,诀窍是让sed重新扫描模式,否则它会在添加SampleInsert的那一行之后错过该行。您需要使用标签并转到标签命令:

$ cat configfile.txt
1 gary     tty7
2 mysearchstringgary     tty7
3 testingmysearchstring gary     tty7
4 gary     tty7mysearchstring
5
6 gary     tty7mysearchstring
7 gary     tty7
8 gary     tty7
$
$
$ sed -r -e ':a;/mysearchstring/ {n;s/$/SampleInsert/};ta' configfile.txt
1 gary     tty7
2 mysearchstringgary     tty7
3 testingmysearchstring gary     tty7SampleInsert
4 gary     tty7mysearchstringSampleInsert
5 SampleInsert
6 gary     tty7mysearchstring
7 gary     tty7SampleInsert
8 gary     tty7
$ 

由于您没有提供测试数据,我刚刚在各个地方编写了一些搜索文本。不要忘记用于测试的空白行。

sed命令使用-r -e args表示扩展的正则表达式。单引号内部是多个命令,由分号分隔。首先设置一个名为a的标签,然后查找与“mysearchstring”匹配的行。如果找到,请运行由大括号括起的命令,并用分号分隔。 n表示将下一行读入模式缓冲区,因为那是您要将文本追加到的行。搜索该行的结尾并追加“SampleInsert”。现在,该行可能具有搜索文本,因此也需要进行搜索。这就是为什么下一个命令是ta,这意味着去标记a。标签a就在搜索搜索字符串之前,这样就可以为搜索模式重新扫描当前行。

编辑:如果在bash脚本中使用,其中搜索和插入值是脚本中定义的变量:

#!/bin/bash

readonly searchstr='mysearchstring'
readonly insertstr='SampleInsert'

sed -r -e ":a;/${searchstr}/ {n;s/$/${insertstr}/};ta" configfile.txt

或者传递给脚本的参数(应该有一些错误处理,但这只是为了说明):

$ fixfile.sh mysearchstr SampleInput

#!/bin/bash

readonly searchstr=$1
readonly insertstr=$2

sed -r -e ":a;/${searchstr}/ {n;s/$/${insertstr}/};ta" configfile.txt

答案 2 :(得分:0)

使用awk:

#!/bin/bash

FIND=".el"; # assign whatever variable you want
APPEND="Hi";
awk -v find="$FIND" -v append="$APPEND" '{print $0 (index($0, find) != 0 ? "\n"append : "")}' configfile.txt
相关问题