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

おすすめ記事