skip to Main Content

This is my text:

    set $domain_name some-not-important-name.com;

I want to reach this:

    set $domain_name test.com;

This is what I tried so far:

DOMAIN_NAME=test.com
awk '{ sub(/ set $domain_name(.*)/, " set $domain_name $DOMAIN_NAME;") }1' file

current result:

    set $domain_name some-not-important-name.com

Update 1

The reason I added multiple whitespaces is that, the line belongs to nginx config and it has multiple spaces.

Since there are both charset and set in my file and they’re not the first character of the line, so I should replace set with space before.

2

Answers


  1. UPDATE: (maintains spacing)

    Setup:

    $ cat file
    ignore this line
        set    $domain_name    some-not-important-name.com;
    ignore this line
    

    One awk idea:

    DOMAIN_NAME=test.com
    
    awk -v dn="${DOMAIN_NAME}" '                                            # set awk variable "dn" to OS variable value
    $1 == "set" && $2 == "$domain_name" { ndx = index($0,$3)                # find location of 3rd field
                                          $0  = substr($0,1,ndx-1) dn ";"   # rebuild current line
                                        }
    1                                                                       # print all lines to stdout
    ' file
    

    Assumptions:

    • there are only 3 white-spaced delimited fields in the line of interest
    • $3 does not match the strings set nor $domain_name
    • $3 does not contain white space

    This generates:

    ignore this line
        set   $domain_name    test.com;
    ignore this line
    

    Original answer: (does not maintain spacing)

    Setup:

    $ cat file
    ignore this line
        set    $domain_name    some-not-important-name.com;
    ignore this line
    

    Assuming the line of interest has just the 3 space-delimited fields …

    One awk idea:

    DOMAIN_NAME=test.com
    
    awk -v dn="${DOMAIN_NAME}" '
    $1 == "set" && $2 == "$domain_name" { $3 = dn ";"}   # redefine the 3rd field as dn + ";"
    1                                                    # print all lines to stdout
    ' file
    
    # or as a one-liner:
    
    awk -v dn="${DOMAIN_NAME}" '$1 == "set" && $2 == "$domain_name" { $3 = dn ";"} 1' file
    

    This generates:

    ignore this line
    set $domain_name test.com;
    ignore this line
    
    Login or Signup to reply.
  2. This would work

    v=' set $domain_name some-not-important-name.com;'
    awk -v d=test.com '{ sub(/ set $domain_name .*/, " set $domain_name " d ";")}1' <<<"$v"
    

    you have to escape the $

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search