0

I tried using this command, but it didn't work for me. If i execute the below command,

 #!/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

I need to add below line, Before 10 line to "Settings for a TLS enabled server" in Nginx.conf file.

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

Looking forward as in the image below. Expecting_result

anandarc
  • 15
  • 4

2 Answers2

0

Try this:

sed -i '10ilocation /nginx-status {\nstub_status on; \nallow all; \n}' $path/nginx.conf

EDIT: This works:

sed -i "$(echo $insert_line)i $(echo $USAGE)" $file_path

hacker315
  • 1,996
  • 2
  • 13
  • 23
0

The easiest is a simple awk in combination with 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
kvantour
  • 25,269
  • 4
  • 47
  • 72