正则探索并用下划线替换特殊字符

发布于 2025-01-22 15:21:43 字数 263 浏览 3 评论 0原文

我深表歉意,因为我知道这已经被问到很多次了。但是,我找不到对我有用的答案!似乎大多数答案似乎都用Java或PHP等特定语言进行了框架。我正在尝试以终点(MAC)线的“纯”正则格式进行此项工作。这一点代码有效,但我想找到特殊的字符并替换为下划线。正如现在,正则毫无替代。知道如何指定替换值?

find . -type f|while read f;do b=${f##*/};mv "$f" "${f%/*}/${b//[^[:alnum:]_.]}";done 

I apologize because I know this has been asked so many times. Yet, I cannot find an answer that works for me! It seems most answers seem framed in a particular language like Java or php. I'm trying to make this work in "pure" regex format at the termimal (mac) line. This bit of code works but I'd like to find special chars and replace with underscores. As it is right now, the regex replaces with nothing. Any idea how I can specify the replace value?

find . -type f|while read f;do b=${f##*/};mv "$f" "${f%/*}/${b//[^[:alnum:]_.]}";done 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ゃ人海孤独症 2025-01-29 15:21:43

您可以在另一个/之后指定替换:

"${f%/*}/${b//[^[:alnum:]_.]/_}"
#                           ↑↑

$ {b // [^[:alnum:] _。字母,数字,下划线和点将被_ char取代。

如果您需要用单个下划线替换一个或多个特殊字符的块

shopt -s extglob
"${f%/*}/${b//+([^[:alnum:]_.])/_}"
shopt -u extglob

You can specify the replacement after another /:

"${f%/*}/${b//[^[:alnum:]_.]/_}"
#                           ↑↑

Here, ${b//[^[:alnum:]_.]/_} means that any single char other than a letter, digit, underscore and dot will be replaced with a _ char.

If you need to replace chunks of one or more special chars with a single underscore use

shopt -s extglob
"${f%/*}/${b//+([^[:alnum:]_.])/_}"
shopt -u extglob
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文