sed: customizing config file header with a defined length?
Here you are a solution:
I use the length of the first dashes line as a length reference.
#! /bin/bash
RSYSLOG_FILENAME="/etc/rsyslog.conf"
awk -v servername="$1" '
/^#+$/ {
ndash = length($0)
print
next
}
/^# SERVER:/ {
str = "# " servername ":/etc/rsyslog.conf"
nspace = ndash - length(str) - 1
if (nspace < 1) { nspace = 1 }
printf("%s%*.*s#\n", str, nspace, nspace, "")
next
}
{
print
}
' "${RSYSLOG_FILENAME}" > "${RSYSLOG_FILENAME}.tmp"
mv "${RSYSLOG_FILENAME}.tmp" "${RSYSLOG_FILENAME}"
UPDATE
For multiple files.
File: ./sysconf.sh
#! /bin/bash
declare -r SERVER_NAME="$1"
shift
for CONF_FILENAME in "${@}"; do
awk -v servername="${SERVER_NAME}" '
/^#+$/ {
ndash = length($0)
print
next
}
/^# SERVER:/ {
match($0, /[: ][^: #]*[ #]/, arr)
fn = arr[0]
gsub(/[: #]/, "", fn)
str = "# " servername ":" fn
nspace = ndash - length(str) - 1
if (nspace < 1) { nspace = 1 }
printf("%s%*.*s#\n", str, nspace, nspace, "")
next
}
{
print
}
' "${CONF_FILENAME}" > "${CONF_FILENAME}.tmp"
mv "${CONF_FILENAME}.tmp" "${CONF_FILENAME}"
done
Used like that:
./sysconf.sh sv4 /etc/rsyslog.conf /etc/mysql/mariadb.cnf