Linux sed:如何在文本块后插入行?
我有一个文本文件:file.confLinux sed:如何在文本块后插入行?,linux,bash,sed,Linux,Bash,Sed,我有一个文本文件: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.
### 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
我试过:
sed --posix -e '/\bLogFile\b/{:a;n;/^ *$/!ba;i\LogFile=/tmp/log1.log' -e '}' file.conf
对于后面有一个空行的选项块,这是很好的
问题是:在最后一个块的末尾,如果没有新行,则不会插入该行。此处显示文本日志文件大小。
如何处理这个问题
$ sed '/#.*LogFile=/a\LogFile=/tmp/log1.log' 1.cat
将做:
# LogFile=
LogFile=/tmp/log1.log
# LogFileSize=1
LogFile=/tmp/log1.log
$ sed '/^$/i\LogFile=/tmp/log1.log' 1.cat
将做:
# LogFile=
LogFile=/tmp/log1.log
# LogFileSize=1
LogFile=/tmp/log1.log
AFAICS,这是因为您告诉它不要在模式中的
LogFile
之后使用\b
,而LogFileSize
与此不匹配,因为Size
是单词的一部分,而不是单词边界。您可能还存在问题,因为当文件中没有行时,n
命令无法读取另一行;我不确定它是做什么的,但它很可能在插入操作发生之前终止命令序列。我忍不住想,如果你把脚本分成多行,它会更容易阅读;作为sed脚本的开始,如果可以使用此选项更改脚本。这不会使LogFileSize像J Lefflerhaps提到的那样通过\bLogFile\b。您需要将您的条件重申为:在一段代码后插入一个空行,当文件的最后一行不是空行时在一段代码后追加。感谢您宝贵的回答。:-)我试图制作一个通用脚本来更改配置文件。但是,不要确保每个配置文件中都会出现类似于#option=like的文本。我的意图是:如果存在一些描述文本,我将在这些行之后添加选项。(我正在以其他方式处理价值置换或新增加的期权。)@donul更新,但如果您不满意,我会考虑)