0

I have the following code:

#!/bin/sh

file_name="webproxy.conf"
echo "#generated code" > $file_name
while read line
do
    eval echo $line >> $file_name
done < "./template.txt"

template.txt:

server {
    listen 80;
    location / {
        proxy_set_header  blabla ;
    }
}

the output in webproxy.conf:

server {
listen 80;
location / {
proxy_set_header  blabla ;
}
}

How can I add the missing spaces in order to prettify the result file

0

You can use this code to format the file at the end:

#!/usr/bin/awk -f

{sub(/^[ \t]+/,"");idx=0}
/\{/{ctx++;idx=1}
/\}/{ctx--}
{id="";for(i=idx;i<ctx;i++)id=sprintf("%s%s", id, "\t");printf "%s%s\n", id, $0}

Demo:

#cat c
server {
listen 80;
location / {
proxy_set_header  blabla ;
}
}

# cat c | ./ngainx_fmt
server {
        listen 80;
        location / {
                proxy_set_header  blabla ;
        }
}

Where ngainx_fmt is the awk script

0

It easiest to use awk for a task like this.

$0 ~ /{/ searches for an opening brace and sets the indent.

$0 ~ /}/ searches for closing brace and reduces the indent.

{ print dent $0 } prints the line, prefixed with the indent.

Spaces indent version

file_name="webproxy.conf"
echo "#generated code" > $file_name

awk 'BEGIN { dent="";nspaces=3}
{ print dent $0 }
$0 ~ /{/ {for (n=0; n<nspaces;n++) dent=dent" "}
$0 ~ /}/ {dent=substr(dent, 0, length(dent)-nspaces)}
' template.txt >> $file_name

Tabs indented version:

file_name="webproxy.conf"
echo "#generated code" > $file_name

awk 'BEGIN { dent=""}
{ print dent $0 }
$0 ~ /{/ {dent=dent"\t"}
$0 ~ /}/ {dent=substr(dent, 0, length(dent)-1)}
' template.txt >> $file_name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.