如何使用shell脚本在文本文件10行之前添加新行以匹配单词

j8ag8udp  于 2023-02-24  发布在  Shell
关注(0)|答案(2)|浏览(150)

我尝试使用这个命令,但它不为我工作。如果我执行下面的命令,

#!/bin/bash

# set the path to your file
file_path="/etc/nginx/nginx.conf"

# set the word you want to search for
search_word="Settings for a TLS enabled server"

# get the line number where the word is found
line_number=$(grep -n "$search_word" $file_path | cut -d: -f1)

# calculate the line number where you want to insert the new line
insert_line=$((line_number-10))

USAGE=$(cat <<-END
    location /nginx-status {
             stub_status on;
             allow all;
    }
END

)

# insert the new line using sed
sed -i "${insert_line}i $USAGE" $file_path

我需要在Nginx.conf文件中的“启用TLS的服务器的设置”中添加以下行,10行之前。

location /nginx-status {
stub_status on; 
allow all; 
}

展望未来,如下图所示。Expecting_result

xkrw2x1b

xkrw2x1b1#

试试这个:
sed -i '10ilocation /nginx-status {\nstub_status on; \nallow all; \n}' $path/nginx.conf
编辑:这很有效:
sed -i "$(echo $insert_line)i $(echo $USAGE)" $file_path

np8igboo

np8igboo2#

最简单的方法是将简单的awk与tac结合使用

awk '(NR==FNR) { to_print=to_print ORS $0; next }
     /Settings for a TLS enabled server/{n=10}
     {print; n--}(n==0){print to_print}
    ' <(tac insert_file.txt) <(tac update_file) | tac > update_file.new
mv update_file.new update_file

相关问题