user3247130
user3247130

Reputation: 71

get a value in a config file regex grep

Using grep I can get a whole line from a config file,

grep <search-pattern> <file>
(eg. grep port config.txt )

but I need the result without the <search-pattern>, and also without any white-space. (For instance, some people may pad the option with spaces or tabs.)

What is the best way to do this?

Finally this method is to be used in a perl script, so perhaps I could do,

$string =~ <whatever>;

and bypass having to execute a command with back-ticks ( `<command>` )

Sample file:

# Replace DOMAINNAME with the "DOMAIN NAME" you want to create a Virtual Host for

server {
    server_name  www.DOMAINNAME;
    rewrite ^(.*) http://DOMAINNAME$1 permanent;
}

server {
        listen 80;
        server_name DOMAINNAME;
                root   /var/www/DOMAINNAME/htdocs;
                index index.php;
        include /etc/nginx/security;

# Logging --
access_log  /var/log/nginx/DOMAINNAME.access.log;
error_log  /var/log/nginx/DOMAINNAME.error.log notice;

        # serve static files directly
        location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt)$ {
            access_log        off;
            expires           max;
        }

        location ~ \.php$ {
        try_files $uri =404;
                fastcgi_pass unix:/var/run/php5-fpm/DOMAINNAME.socket;
                fastcgi_index index.php;
                include /etc/nginx/fastcgi_params;
        }
}

I want to get the value of the listen port (80, in this case).

Upvotes: 0

Views: 3126

Answers (3)

ChrisN
ChrisN

Reputation: 431

You can use just sed for this, no need to pipe from grep

sed -nr 's/^\s*listen\s+([0-9]+)\s*;$/\1/p' $nginxconfig

And you would put that into a variable thusly

myListeningPort="$(sed -nr 's/^\s*listen\s+([0-9]+)\s*.*;$/\1/p' $nginxconfig)"

Replace $nginxconfig with your config file or set the variable to your file location. This is versatile such that you can replace the directive key (listen in this case) with another that would contain a numeric value and it ignores leading spaces, invalid/incomplete lines (missing trailing ";"), and commented lines.

You can make it more generic by changing the capture group from just 0-9 to alphanumeric and other characters.

Upvotes: 0

user3620917
user3620917

Reputation:

To get number 80 from the given sample you can do it with pure grep:

$ grep -Po '\blisten\s*\K[^;]*' file
80

Upvotes: 0

Bohemian
Bohemian

Reputation: 425043

Pipe it to sed:

grep port config.txt | sed 's/port\| \| ;//g'

The sed command means "substitute 'port' or ' ' or ';' with nothing", and "g" means "global" (all matches).

Upvotes: 2

Related Questions