我想使用sed来删除和替换bash脚本中的一些字符。
#!/bin/bash
DIR="."
file_extension=".mkv|.avi|.mp4"
files= `find $DIR -maxdepth 1 -type f -regex ".*\.\(mkv\|avi\|mp4\)" -printf "%f\n"`为了简化$files,我想在其中使用$file_extension,即将.mkv|.avi|.mp4更改为mkv|avi|mp4
我如何使用sed来做到这一点呢?或者是一种更简单的选择?
发布于 2021-02-21 20:00:23
不需要sed;bash内置了基本的替换运算符。全部替换操作的基本语法是${variable//pattern/replacement},但不幸的是它不能嵌套,所以您需要一个帮助变量。为了清楚起见,我甚至使用了两个:
file_extension_without_dot="${file_extension//./}" # mkv|avi|mp4
file_extension_regex="${file_extension_without_dot//|/\\|}" # mkv\|avi\|mp4
files= `find $DIR -maxdepth 1 -type f -regex ".*\.\($file_extension_regex\)" -printf "%f\n"`如果你的find支持它,你也可以考虑使用不同的-regextype (参见find -regextype help),这样你就不再需要这么多的反斜杠了。
https://stackoverflow.com/questions/66301963
复制相似问题