【问题标题】:grep command deletes all dirs and not just dirs matching regex?grep 命令删除所有目录,而不仅仅是匹配正则表达式的目录?
【发布时间】:2016-03-03 23:49:34
【问题描述】:

我正在使用 Linux/grep 命令并正在创建一个“清理”bash 脚本,该脚本会删除 与特定正则表达式模式匹配的目录。

命令是:ls | grep -v "\[([a-zA-Z]){0,}\]/g" | xargs -d"\n" rm -rf

并且此处图片中所有没有突出显示的目录名称应该是被删除的目录名称;但是,上面的命令最终会删除 all 我当前目录中的文件夹/文件

我的正则表达式模式或管道命令的方式有问题吗?我已尝试删除 rm -rf,但这并没有删除任何内容。

正则表达式模式匹配目录名称,如下所示:

这是我在http://regex101.com上测试时使用的一组目录名

Challenge #96 [difficult] (Water Droplets)/
Challenge #96 [easy] (Controller Chains)/
Challenge #96 [intermediate] (Parsing English Values)/
Challenge #99 [difficult] (Animated unemployment map of the United States)/
Challenge #99 [easy] (Words with letters in alphabetical order)/
Challenge #99 [intermediate] (Unemployment map of the United States)/
Challenge 208 [Bonus] The Infinite Stallman Theorem/
Challenge#172 [Intermediate] Image Rendering 101...010101000101/
Challenge#180 [Easy] Look'n'Say/
Contest #1 - IDE Intellisense/
EXTENSIONS: Week-Long Challenge #1 due FRIDAY!
Honour Roll #1/
New moderator needed/
News, Mods, getting Wiki with it/
REMINDER: Week-Long Challenge #1 due today!
There are gonna be some changes here/
This isn't a challenge, just a thank you/
WINNERS: Week-Long Challenge #1
WINNERS: Week-Long Challenge #2
Want to contribute to this subreddit?
We need some feedback!/
Week-Long Challenge #1: Make a (tiny) video game!
[Discussion] Challenge tags [Easy] [Intermediate] [Hard]/
[Easy] Longest Two-Character Sub-String/
[Extra] Poetic Justice/
[Mod Post] Do you want a 4-hour, 24-hour, or 48-hour programming challenge set?
[Request] The Ultimate Wordlist/
[Weekly #11] Challenges you want/
[Weekly #12] Learning a new language/
[Weekly #16] Standards and Unwritten Standards/
[Weekly #17] Mini Challenges/
[Weekly #21] Recap and Updates/
[Weekly #22] Machine Learning/
[Weekly #23] Computational Complexity and Algorithm Design/
[Weekly #24] Mini Challenges/
[Weekly #2] Pre-coding Work/
[Weekly #6] Python Tips and Tricks/
[Weekly #8] Sorting algorithms/
[Weekly] #1 -- Handling Console Input/
[difficult] challenge #1/
[difficult] challenge #2/
[easy] challenge #1/
[easy] challenge #2/
[intermediate] challenge #2/
challenge #3 [difficult]/
cleanup-clone.sh*
cleanup.sh*
for the artistically inclined... Have something extra!

【问题讨论】:

  • xargs 将根据空格拆分它接收到的参数,并且您的路径中有一些。我建议使用带有 -print0 标志的“find”命令并将其与 xargs 中的 -0 标志结合使用。我现在无法访问命令提示符来给你举个例子。

标签: regex bash grep


【解决方案1】:

是的,你的正则表达式是错误的。以下命令对我有用:

ls | grep -v "\[[a-zA-Z]*\]" | xargs -d"\n" rm -rf

看,使用grep 命令,使用g 修饰符没有任何意义,因为grep 每次运行正则表达式模式时只输入一行输入。此外,{0,}* 量词相同。

提示:在尝试删除所有目录之前,根据您的设置可能会遇到什么麻烦,只需运行与您匹配的命令相反的操作,如下所示:

ls | grep "\[([a-zA-Z]){0,}\]/g"

这样您就可以知道不会被删除的目录列表。对于您的原始正则表达式,该列表为空。

这个命令比图像中显示的目录要多,因为你的正则表达式匹配的不仅仅是这些目录,但我敢打赌你已经知道了。你可以看到匹配目录的完整列表here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    相关资源
    最近更新 更多