エンジニアとしての市場価値を測りませんか?PR

企業からあなたに合ったオリジナルのスカウトを受け取って、市場価値を測りましょう

102
70

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

findとxargsコマンドで-print0オプションを使う理由(改)

Posted at

findの-print0とxargsの-0
findとxargsのサンプルを調べていると初めは誰もが疑問に思う謎のオプション。
例えばこんなコマンド。

    $ find . -name '*.bak' -print0 | xargs -0 rm

find print0でググると、トップにでてきたのは下のサイト。

UNIX findとxargsコマンドで-print0オプションを使う理由

よくまとまっていてわかりやすいのですが、下記の部分に誤りがあります。

lsコマンドの結果からわかるように、スペースが含まれるファイル名は、別々なものとして認識されています。
この問題は、findコマンドが区切り文字としてスペースを使っているからです。

findコマンドが区切り文字としてスペースを使っているのではなく、正しくはxargsが区切り文字として空白文字(改行、スペース、タブなど)を使っているからです。

つまり、下のサンプルが示すように、空白と改行の両方を区切り文字として扱ってしまうわけです。

$ echo -e "Hello World\nHelloWorld" | xargs -n1 echo
Hello
World
HelloWorld

処理の前後関係としては、xargsが空白文字でなくヌル文字を区切りとして扱うように-0を指定し、xargsの形式に合わせるためにfindの-print0を指定する、という順番で考えた方がシックリくるのではないでしょうか。

参考サイト

102
70
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
102
70

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?