Awk: either modify or add a string based on its existence

I have a small awk script that makes some changes to a local file (to a Java file .properties

to give you an idea). This is the part of the deployment script that affects the user group.

I want to be able to set defaults while leaving the rest of the file in user preferences. This means adding a config line if it's missing, modifying it if it's present, leaving everything else as it is.

I am currently using something like this:

# initialize
BEGIN {
  some_value_set      = 0
  other_value_set     = 0

  some_value_default  = "some.value=SOME VALUE"
  other_value_default = "other.value=OTHER VALUE"
}

# modify existing lines
{
  if (/^some\.value=.*/) 
  {
    gsub(/.*/, some_value_default)
    some_value_set = 1
  }
  else if (/^other\.value=.*/)
  {
    gsub(/.*/, other_value_default)
    other_value_set = 1
  }
  print $0
}

# append missing lines
END {
  if (some_value_set   == 0) print some_value_default
  if (other_value_set  == 0) print other_value_default
}

      

Especially when the number of lines that I want to control increases, it becomes more and more cumbersome. My knowledge of awk is not that great and the above is just not the case - how can I simplify this?

PS: If possible, I would like to stay with awk. Please don't just recommend using Perl / Python / it will be much easier. :-)

+1


a source to share


2 answers


BEGIN {
    defaults["some.value"]  = "SOME VALUE"
    defaults["other.value"] = "OTHER VALUE"
}

{
    for (key in defaults) {
        pattern = key
        gsub(/\./, "\\.", pattern)
        if (match($0, "^" pattern "=.*")) {
            gsub(/=.*/, "=" defaults[key])
            delete defaults[key]
        }
    }
    print $0
}

END {
    for (key in defaults) {
        print key "=" defaults[key]
    }
}

      



+4


a source


My AWK is rusty so I won't provide a valid code.



  • Initialize an array using regular expressions and values.
  • For each row, array iteration and corresponding substitutions. Clean up used records.
  • Finally, iterate through the array and add strings for the rest of the entries.
+2


a source







All Articles