次のようにPHPファイルのコードブロックを自動的にコメントアウトしたいと思います。
元のブロック:
// Enable all errors
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(E_ALL);
新しいコメントブロック:
/* For the production version, the following codelines are commented
out
// Enable all errors
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(E_ALL);
*/
したがって、この行を2つのファイルに入れ、sedを使用して自動的に置き換えを行います。ところがインターネットで検索した結果、やっと見つけました。sedを使用して文字列をファイルの内容に置き換えるそしてsed - 文字列をファイルの内容に置き換えるつまり、ソースまたはターゲットスキーマだけが1つのファイルにあり、残りはオンラインファイルにあることを意味します。ただし、ファイルには両方のサンプルがありません。
それでは、交換する方法は何ですか? sedを使うべきか、それともawkを使うべきですか?
ベストアンサー1
sed
このメソッドsed
はリテラル文字列を理解していないため、使用しないでください(参照sedを使用して正規表現のメタ文字を確実にエスケープすることは可能ですか?)、そのようなツールを使用してawk
リテラル文字列を理解することは実際に可能です。
GNUを使用したawk
複数文字のRS
合計ARGIND
:
$ awk -v RS='^$' -v ORS= '
ARGIND < 3 { a[ARGIND]=$0; next }
s = index($0,a[1]) {
$0 = substr($0,1,s-1) a[2] substr($0,s+length(a[1]))
}
{ print }
' old new file
this is
the winter
/* For the production version, the following codelines are commented
out
// Enable all errors
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(E_ALL);
*/
of our
discontent
または、次のいずれかを使用してくださいawk
。
$ awk '
FNR == 1 { a[++argind]=$0; next }
{ a[argind] = a[argind] ORS $0 }
END {
$0 = a[3]
if ( s = index($0,a[1]) ) {
$0 = substr($0,1,s-1) a[2] substr($0,s+length(a[1]))
}
print
}
' old new file
this is
the winter
/* For the production version, the following codelines are commented
out
// Enable all errors
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(E_ALL);
*/
of our
discontent
上記は以下の入力ファイルを使用して実行されました。
$ head old new file
==> old <==
// Enable all errors
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(E_ALL);
==> new <==
/* For the production version, the following codelines are commented
out
// Enable all errors
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(E_ALL);
*/
==> file <==
this is
the winter
// Enable all errors
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(E_ALL);
of our
discontent