Linux

awk + 僅當文件中未定義行時才在擷取的單詞之前附加行

  • August 7, 2018

以下awk語法將文件中的 3 行添加到帶有單詞 - ‘DatePattern’ 的行之前:

$ 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

你可以這樣做:

# 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

引用自:https://unix.stackexchange.com/questions/460833