Linux CLIを介してファイル内の電子メールアドレスを見つけたことに基づいて、誤った電子メールを削除しようとしています。
私はファイルを取得できます
find . | xargs grep -l email@domain.com
しかし、次のコードが機能しないため、そこからそれらを削除する方法を理解できません。
rm -f | xargs find . | xargs grep -l email@domain.com
ご協力いただきありがとうございます。
Linux CLIを介してファイル内の電子メールアドレスを見つけたことに基づいて、誤った電子メールを削除しようとしています。
私はファイルを取得できます
find . | xargs grep -l email@domain.com
しかし、次のコードが機能しないため、そこからそれらを削除する方法を理解できません。
rm -f | xargs find . | xargs grep -l email@domain.com
ご協力いただきありがとうございます。
安全のために、私は通常、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
@MartinBeckettが優れた回答を投稿しました。そのガイドラインに従ってください
あなたのコマンドの解決策:
grep -l email@domain.com * | xargs rm
または
for file in $(grep -l email@domain.com *); do
rm -i $file;
# ^ prompt for delete
done
find
's-exec
とを使用できます。コマンドが成功した-delete
場合にのみファイルが削除されます。何も出力されないようにgrep
使用すると、をに置き換えて、文字列が含まれているファイルを確認できます。grep -q
-q
-l
find . -exec grep -q 'email@domain.com' '{}' \; -delete
マーティンの安全な答えにもかかわらず、スクリプトの作成など、削除したいものが確実にある場合は、これを使用して、このあたりでこれまでに提案された他のワンライナーよりも大きな成功を収めました。
$ find . | grep -l email@domain.com | xargs -I {} rm -rf {}
しかし、私はむしろ名前で見つけます:
$ find . -iname *something* | xargs -I {} echo {}
rm -f `find . | xargs grep -li email@domain.com`
仕事はうまくいきます。`...`を使用してコマンドを実行し、email。@ domain.comを含むファイル名を提供し(grep -lはそれらをリストし、-iは大文字と小文字を区別しません)、rm(-f強制/ -iインタラクティブ)でそれらを削除します。
私は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'
find . | xargs grep -l email@domain.com
削除する方法:
rm -f 'find . | xargs grep -l email@domain.com'