\n
usingを置き換えるためにパターンを追加すると、一致しないsed
ことがわかりました。例:
$ cat > alpha.txt
This is
a test
Please do not
be alarmed
$ sed -i'.original' 's/a test\nPlease do not/not a test\nBe/' alpha.txt
$ diff alpha.txt{,.original}
$ # No differences printed out
どのように動作させることができますか?
ベストアンサー1
最も簡単な呼び出しでsed、それは一つパターン空間のテキスト行。\n
入力から区切られたテキストの1行。パターンスペースには1行もありません\n
。だから正規表現が何も見つからないのです。
複数の行をパターン空間に読み込んで驚くほどうまく操作できますが、通常よりもはるかに多くの努力が必要です。 Sedにはこの種の操作を許可するコマンドセットがあります...ここにリンクがありますsed コマンドの要約。これは私が見つけたものの中で最高であり、私を興奮させます。
しかし、sedのマイクロコマンドを使い始めたら、「一行」の概念を忘れてください。感じを得るまで、構造化されたプログラムのように配置すると便利です。とてもシンプルながらもユニークです。テキスト編集の「アセンブリ言語」と考えればいいのです。
要約:簡単な作業にはsedを使用してください。たぶんそれ以上であるかもしれませんが、一般的に1行を使用するよりも多くの場合、ほとんどの人は他のものを好みます
。オプションは(私はsedを使用しますが、それは私がPerlをよく知らないからです)。
sed '/^a test$/{
$!{ N # append the next line when not on the last line
s/^a test\nPlease do not$/not a test\nBe/
# now test for a successful substitution, otherwise
#+ unpaired "a test" lines would be mis-handled
t sub-yes # branch_on_substitute (goto label :sub-yes)
:sub-not # a label (not essential; here to self document)
# if no substituion, print only the first line
P # pattern_first_line_print
D # pattern_ltrunc(line+nl)_top/cycle
:sub-yes # a label (the goto target of the 't' branch)
# fall through to final auto-pattern_print (2 lines)
}
}' alpha.txt
ここで同じスクリプトがはっきりと読みやすく難しい内容に圧縮されていますが、一部ではこれをあいまいに呼ぶこともあります。一行
sed '/^a test$/{$!{N;s/^a test\nPlease do not$/not a test\nBe/;ty;P;D;:y}}' alpha.txt
これは私のコマンド「チートシート」です
: # label
= # line_number
a # append_text_to_stdout_after_flush
b # branch_unconditional
c # range_change
d # pattern_delete_top/cycle
D # pattern_ltrunc(line+nl)_top/cycle
g # pattern=hold
G # pattern+=nl+hold
h # hold=pattern
H # hold+=nl+pattern
i # insert_text_to_stdout_now
l # pattern_list
n # pattern_flush=nextline_continue
N # pattern+=nl+nextline
p # pattern_print
P # pattern_first_line_print
q # flush_quit
r # append_file_to_stdout_after_flush
s # substitute
t # branch_on_substitute
w # append_pattern_to_file_now
x # swap_pattern_and_hold
y # transform_chars