Skip to content

Instantly share code, notes, and snippets.

@dk949
Created September 29, 2023 18:53
Show Gist options
  • Save dk949/95b968a94f51756d0b43f28f6ba031cc to your computer and use it in GitHub Desktop.
Save dk949/95b968a94f51756d0b43f28f6ba031cc to your computer and use it in GitHub Desktop.
Parse config file with awk. Get all lines listed under a key.
# When given a conf file, will look for key "[key]" and print the non-blank,
# lines until the next key or until the end of the file.
#
# All comments are removed as well as leading and trailing spaces
#
# Expects an input variable 'key' (can be passed using `awk -v key="your key here"`)
#
#
# Example:
#
# # file.conf
# [some-key] # comment
#
#
# line 1
#
# line 2 # another comment
#
#
# [some-other-key]
# ...
#
# $ awk -f get_conf_key.awk -v key="some-key" file.conf
# > [some-key]
# > line 1
# > line 2
#
#
# Note: The first line of the output will be the key itself, even if there are
# no entires for it. If nothing is printed - the key could not be found.
function rm_comments_and_space(str) {
sub(/[[:space:]]*(#.*)?$/,"", str)
sub(/^[[:space:]]*/,"", str)
return str
}
/\[/ {
line = rm_comments_and_space($0)
regex = "^\\[" key "\\]$"
if (line ~ regex) do_print = 1
else do_print = 0
}
do_print {
if ($0 !~ /^[[:space:]]*$/ && $0 !~ /^[[:space:]]*#/) {
line = rm_comments_and_space($0)
print line
}
}
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <https://unlicense.org>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment