Question

I need help with extracting and then reinserting a specific block of text from a configuration file. The block I am interested in starts with "server_name" and ends with a ";"

server_name   example.com  
              www.example.com
              anothername.co.uk; 

I think sed or awk commands could do this but I am not sure where to start. Ideally I would like to get "example.com" "www.example.com" and "anothername.co.uk" read into a bash array.

I am making a shell script to control a web server and want to be able to edit the host headers for each site, so I want to read in the host headers from the file into an array so that I can prompt the user if they want to delete or add and hosts. Then I want to write the edited host headers back into the file.

Using Jotne's awk command I can now read in the host headers. So It's just writing them back to the file that I need help with.

I didn't realise but there varying amounts of white spaces at the start of each of the lines that I am trying to read in. We have 100's of websites that have been edited manualy in the past. I'd appreciate any help.

Was it helpful?

Solution

This awk should do:

arr=($(awk '/^server_name/ {f=1} f {p=$NF;sub(/;$/,"",p);print p} /;$/ {f=0}' file))
echo ${arr[0]}
example.com
echo ${arr[1]}
www.example.com
echo ${arr[2]}
anothername.co.uk

It will get all text starting form server_name and ends with ; into an bash array

Or you can store them in an internal awk array, and then write them to another file:

awk '/^server_name/ {f=1} f {p=$NF;sub(/;$/,"",p);a[++c]=p} /;$/ {f=0} END {for (i=1;i<=c;i++) print a[i]}' file > newfile
cat newfile
example.com
www.example.com
anothername.co.uk
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top