もた日記

くだらないことを真面目にやる

Linuxメモ : Rust製のsdコマンド(sedの代替)を試してみる

sd

github.com

Rust製のsdコマンドはsedコマンドの代わりとして使えそうなコマンド。
直感的に書けることと高速なのが特徴とのこと。

f:id:wonder-wall:20190311211939p:plain

インストール

各環境でのインストール方法はこのページに書いてある。
バイナリはこのページからダウンロードでき、 Rust製なのでcargo installでインストールできる。

$ cargo install sd

ヘルプメッセージ。

$ sd -h
sd 0.5.0

USAGE:
    sd [OPTIONS] <find> <replace_with> [files]...

OPTIONS:
    -f, --flags <flags>
            Regex flags. May be combined (like `-f mc`).

            c - case-sensitive
            m - multi-line matching
            i - case-insensitive

            Smart-case is enabled by default.
    -h, --help
            Prints help information

    -i, --in-place
            Modify the files in-place. Otherwise, transformations will be emitted to STDOUT by default.

    -s, --string-mode
            Treat expressions as non-regex strings.


ARGS:
    <find>
            The regexp or string (if -s) to search for.

    <replace_with>
            What to replace each match with. Unless in string mode, you may use captured values like $1, $2, etc.

    <files>...
            The path to file(s). This is optional - sd can also read from STDIN.

使い方

基本的な使い方は以下の通り。

$ cat test.txt
abcABCabcABC
$ sed s/abc/012/g test.txt
012ABC012ABC
$ sd abc 012 test.txt 
012012012012

デフォルトではsmart caseでマッチするので、大文字小文字を区別する/区別しないは下記オプションを指定する。

$ sd -f c abc 012 test.txt
012ABC012ABC
$ sd -f i ABC 012 test.txt
012012012012

ファイルを上書きする場合は-iオプションが使える。

$ cat test.txt
abcABCabcABC
$ sd -i abc 012 test.txt
$ cat test.txt
012012012012

正規表現を使うこともでき、

$ echo 'abc   ' | sd '\s+$' ''
abc

-sオプションを指定すると正規表現を無効にできる。

$ echo 'abc((([])))' | sd -s '((([])))' ''
abc

その他、Readmeに書いてあったサンプルとしてはキャプチャグループや、

$ echo 'cargo +nightly watch' | sd '(\w+)\s+\+(\w+)\s+(\w+)' 'cmd: $1, channel: $2, subcmd: $3'
cmd: cargo, channel: nightly, subcmd: watch

fdコマンドと組み合わせた一括置換の方法など。

for file in $(fd -t f); do
  cp "$file" "$file.bk"
  sd -i 'from "react"' 'from "preact"' "$file"; 
done

wonderwall.hatenablog.com