ここで利用可能な以前の質問をいくつか見つけようとしましたが、残念ながら正確なケースが見つかりませんでした。
他のコマンドの出力から次のような結果を得たいと思います。
pattern.d
17.91
17.55
pattern.b
pattern.a
7.21
9.34
pattern.c
これに関して:
pattern.d
17.91
17.55
pattern.b
1000
pattern.a
7.21
9.34
pattern.c
1000
もう少し説明しようとしています。 "pattern"という文字列を含む各行の後には常に数字が必要です。そうでない場合は、値が1000の新しい行を挿入したいと思います。
パターンには、後で内容をアルファベット順に並べ替えるのに役立つ変更される「拡張子」(.a .b .c .dですが、「拡張子」の数字はありません)があります。
編集:答えを受け入れましたが、まだ別のバリエーションを探している人がいる場合は、「パターン」が異なるように指定する必要があります。
pattern.a
pattern.d
pattern.c
pattern.d
pattern.b
17.91
ベストアンサー1
以下は、sed
すべての入力(たとえば、複数の連続した一致pattern
)に対して機能するソリューションです。
sed '1{ # when on first line
x # exchange
s/^/1000/ # replace the empty hold buffer with "1000"
x # exchange back
}
: do # label "do"
/pattern/{ # if the current line matches "pattern"
${ # if we're on the last line
G # append hold buffer content to pattern space
b # go to end of script
}
n # otherwise print and pull in the next line
/^[[:digit:]]/!{ # if this one doesn't start with a digit
x # exchange
p # print (the pattern space is now "1000")
x # exchange back
b do # go to label "do"
}
}' infile
それでgnu sed
私達は書くことができます
sed '1{x;s/^/1000/;x};:b;/pattern/{${G;b};n;/^[[:digit:]]/!{x;p;x;bb}}' infile
次のようにすることができますawk
:
awk -vc=0 '!/^[[:digit:]]/{
if (c) {print "1000"}
}
{ if (/pattern/){c=1} else{c=0}
}
END{if (c){print "1000"}
};1' infile
つまり、c=1
一致する行に設定しpattern
、c=0
残りの行に設定し、数字で始まらないすべての行に設定し(ブロック内END
)c
、すでに設定されていること(または1
前の行が一致することを意味pattern
)を確認します。 printなら1000
。