2

I have text file: file.conf

### Option: LogFile
#       Name of log file.
#       If not set, syslog is used.
#
# Mandatory: no
# Default:
# LogFile=

### Option: LogFileSize
#       Maximum size of log file in MB.
#       0 - disable automatic log rotation.
#
# Mandatory: no
# Range: 0-1024
# Default:
# LogFileSize=1

I want to search for a line containing LogFile, skip subsequent non-blank lines, and insert a new line with predefined content just before the next blank line.

And I have tried:

sed --posix -e '/\bLogFile\b/{:a;n;/^ *$/!ba;i\LogFile=/tmp/log1.log' -e '}' file.conf

And this is working fine, for those option blocks which are followed by a blank line. However, it is also possible that the file ends with no blank line, in which case I want to insert the new line at the end of the file. In this example, it would happen if I was looking for LogFileSize instead of LogFile.

How can I handle this case?

1
  • What sed are you using? The given command does nothing. What should the output look like?
    – Kusalananda
    Commented Sep 24, 2017 at 17:50

2 Answers 2

0

A simple possibility would be to

echo >>file.conf

after sed execute I'm not sure it's possible with pure sed

0

You're running inte issues because you're using i ("insert") rather than a ("append"). i insert before a selected line while a appends after.

You are also matching the block by the Option: LogFile header rather than the more appropriately placed line with the default value (# LogFile=).


Using GNU sed:

$ sed '/^# LogFile=/a\LogFile=/tmp/log1.log' file.conf
### Option: LogFile
#       Name of log file.
#       If not set, syslog is used.
#
# Mandatory: no
# Default:
# LogFile=
LogFile=/tmp/log1.log

### Option: LogFileSize
#       Maximum size of log file in MB.
#       0 - disable automatic log rotation.
#
# Mandatory: no
# Range: 0-1024
# Default:
# LogFileSize=1

This works with LogFileSize as well:

$ sed '/^# LogFileSize=/a\LogFileSize=512' file.conf
### Option: LogFile
#       Name of log file.
#       If not set, syslog is used.
#
# Mandatory: no
# Default:
# LogFile=

### Option: LogFileSize
#       Maximum size of log file in MB.
#       0 - disable automatic log rotation.
#
# Mandatory: no
# Range: 0-1024
# Default:
# LogFileSize=1
LogFileSize=512

Both in one go:

$ sed -e '/^# LogFileSize=/a\LogFileSize=512' -e '/^# LogFile=/a\LogFile=/tmp/log1.log' file.conf

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .