55

Linux CLIを介してファイル内の電子メールアドレスを見つけたことに基づいて、誤った電子メールを削除しようとしています。

私はファイルを取得できます

find . | xargs grep -l email@domain.com

しかし、次のコードが機能しないため、そこからそれらを削除する方法を理解できません。

rm -f | xargs find . | xargs grep -l email@domain.com

ご協力いただきありがとうございます。

4

7 に答える 7

78

安全のために、私は通常、findからawkのようなものに出力をパイプし、各行が「rmfilename」であるバッチファイルを作成します。

そうすれば、実際に実行する前に確認して、正規表現で実行するのが難しい奇妙なエッジのケースを手動で修正できます。

find . | xargs grep -l email@domain.com | awk '{print "rm "$1}' > doit.sh
vi doit.sh // check for murphy and his law
source doit.sh
于 2010-12-25T02:58:05.117 に答える
77

@MartinBeckettが優れた回答を投稿しました。そのガイドラインに従ってください

あなたのコマンドの解決策:

grep -l email@domain.com * | xargs rm

または

for file in $(grep -l email@domain.com *); do
    rm -i $file;
    #  ^ prompt for delete
done
于 2010-12-25T03:01:27.533 に答える
17

find's-execとを使用できます。コマンドが成功した-delete場合にのみファイルが削除されます。何も出力されないようにgrep使用すると、をに置き換えて、文字列が含まれているファイルを確認できます。grep -q-q-l

find . -exec grep -q 'email@domain.com' '{}' \; -delete
于 2010-12-25T03:27:41.957 に答える
3

マーティンの安全な答えにもかかわらず、スクリプトの作成など、削除したいものが確実にある場合は、これを使用して、このあたりでこれまでに提案された他のワンライナーよりも大きな成功を収めました。

$ find . | grep -l email@domain.com | xargs -I {} rm -rf {}

しかし、私はむしろ名前で見つけます:

$ find . -iname *something* | xargs -I {} echo {}
于 2014-07-08T23:40:12.073 に答える
3
rm -f `find . | xargs grep -li email@domain.com`

仕事はうまくいきます。`...`を使用してコマンドを実行し、email。@ domain.comを含むファイル名を提供し(grep -lはそれらをリストし、-iは大文字と小文字を区別しません)、rm(-f強制/ -iインタラクティブ)でそれらを削除します。

于 2017-08-06T08:43:45.647 に答える
3

私はMartinBeckettのソリューションが好きでしたが、スペースを含むファイル名がそれをつまずかせる可能性があることがわかりました(ファイル名にスペースを使用する人のように、pfft:D)。また、一致したものを確認したかったので、「rm」コマンドでファイルを削除するのではなく、一致したファイルをローカルフォルダーに移動しました。

# Make a folder in the current directory to put the matched files
$ mkdir -p './matched-files'

# Create a script to move files that match the grep
# NOTE: Remove "-name '*.txt'" to allow all file extensions to be searched.
# NOTE: Edit the grep argument 'something' to what you want to search for.

$ find . -name '*.txt' -print0 | xargs -0 grep -al 'something' | awk -F '\n' '{ print "mv \""$0"\" ./matched-files" }' > doit.sh

Or because its possible (in Linux, idk about other OS's) to have newlines in a file name you can use this longer, untested if works better (who puts newlines in filenames? pfft :D), version:

$ find . -name '*.txt' -print0 | xargs -0 grep -alZ 'something' | awk -F '\0' '{ for (x=1; x<NF; x++) print "mv \""$x"\" ./matched-files" }' > doit.sh

# Evaluate the file following the 'source' command as a list of commands executed in the current context:
$ source doit.sh

注:utf-16エンコーディングのファイル内でgrepが一致しないという問題がありました。回避策については、こちらをご覧ください。Webサイトが表示されなくなった場合は、grepの-aフラグを使用して、grepにファイルをテキストとして処理させ、各拡張文字の最初のバイトに一致する正規表現パターンを使用します。たとえば、Entitéと一致させるには、次のようにします。

grep -a 'Entit.e'

それがうまくいかない場合は、これを試してください:

grep -a 'E.n.t.i.t.e'
于 2017-11-23T08:01:26.857 に答える
1
find . | xargs grep -l email@domain.com

削除する方法:

rm -f 'find . | xargs grep -l email@domain.com'
于 2016-03-14T07:35:29.943 に答える