sedとregexを使ってファイル内の文字列を見つけて置き換える方法は?

sedとregexを使ってファイル内の文字列を見つけて置き換える方法は?

次の種類の行を含むファイルがあります。

find /home/subd1/subd2/$dirname -type d 
find /home1/subd1/subd2/$dirname -type d 
find /home10/subd1/subd2/$dirname -type d 

/home/orを見つけてDIFFERENTまたは/home<no>/に変更したいと思います。デフォルトでは検索と置換 -/home//home<no>/

/home with /home2 or
/home2 with /home3 or
/home3 with /home
etc.

私は〜しようとする -

sed -i 's/\/home.?\//\/home3\//g' /path/to/file
sed -i 's/\/home[\d]?\//\/home3\//g' /path/to/file

しかし、これはファイルを変更しませんでした。ここで何か抜けましたか?ありがとう

ベストアンサー1

\dサポートしていませんsed[0-9]選択肢を試してみてください。

たとえば、提供したサンプルファイルを試してみました。

find /home/subd1/subd2/$dirname -type d 
find /home1/subd1/subd2/$dirname -type d 
find /home10/subd1/subd2/$dirname -type d 

与えられた場合sed -i 's;/home[0-9]*/;/home3/;g' test.txt;各項目をエスケープする必要がないようにsed区切り文字として使用されます)、/ファイルは次のように編集されます。

find /home3/subd1/subd2/$dirname -type d 
find /home3/subd1/subd2/$dirname -type d 
find /home3/subd1/subd2/$dirname -type d 

これが変わるという点は注目に値する。すべて/home/とインスタンスは/home<no>/同じ新しい値です(この場合/home3/)。これはあなたの目標だと思いますが、そうでない場合は他のsed表現方法が必要になります。

おすすめ記事