awk + ​​仅当文件中未定义行时才在捕获的单词之前附加行

awk + ​​仅当文件中未定义行时才在捕获的单词之前附加行

以下awk语法将在文件中的包含单词“DatePattern”的行之前添加 3 行:

$ awk 'done != 1 && /DatePattern/ {
    print "log4j.appender.DRFA=org.apache.log4j.RollingFileAppender"
    print "log4j.appender.DRFA.MaxBackupIndex=100"
    print "log4j.appender.DRFA.MaxFileSize=10MB"
    done = 1
    } 1' file >newfile && mv newfile file

问题是awk不关心行是否已经存在,那么需要添加什么到awk,以便仅在行尚不存在时插入行?

其他例子

在本例中,我们要在包含“HOTEL”一词的行之前添加名称“trump”、“bush”和“putin”,但仅限于这些名称不存在的情况:

$ awk 'done != 1 && /HOTEL/ {
    print "trump"
    print "bush"
    print "putin"
    done = 1
    } 1' file >newfile && mv newfile file

答案1

您可以按如下方式执行此操作:

# store the 3 lines to match in shell variables
line_1="log4j.appender.DRFA=org.apache.log4j.RollingFileAppender"
line_2="log4j.appender.DRFA.MaxBackupIndex=100"
line_3="log4j.appender.DRFA.MaxFileSize=10MB"

# function that escapes it's first argument to make it palatable
# for use in `sed` editor's `s///` command's left-hand side argument
esc() {
    printf '%s\n' "$1" | sed -e 's:[][\/.^$*]:\\&:g'
}

# escape the lines
line_1_esc=$(esc "$line_1")
line_2_esc=$(esc "$line_2")
line_3_esc=$(esc "$line_3")

# invoke `sed` and fill up the pattern space with 4 lines (rather than the default 1)
# then apply the regex to detect the presence of the lines 1/2/3.
sed -e '
    1N;2N;$!N
    '"/^$line_1_esc\n$line_2_esc\n$line_3_esc\n.*DatePattern/"'!D
    :a;n;$!ba
' input.file

答案2

基于名称的顺序无关紧要的假设,并且它们总是以三个一组出现,尝试

awk '
BEGIN           {INSTXT = "trump" ORS "bush" ORS "putin"
                 for (n = split (INSTXT, T, ORS); n; n--) PRES[T[n]]
                }

!(LAST in PRES) &&
/HOTEL/         {print INSTXT
                }

                {LAST = $0
                }
1
' file

相关内容