简体   繁体   English

Bash/sed - 在变量中使用 sed

[英]Bash/sed - use sed in variable

I would like to use sed to delete and replace some characters in a bash script.我想使用 sed 删除和替换 bash 脚本中的一些字符。

#!/bin/bash
DIR="."
file_extension=".mkv|.avi|.mp4"
files= `find $DIR -maxdepth 1 -type f -regex ".*\.\(mkv\|avi\|mp4\)" -printf "%f\n"`

In order to simplify $files, I would like to use $file_extension in it, ie change.mkv|.avi|.mp4 to mkv\|avi\|mp4为了简化$files,我想在里面使用$file_extension,即把.mkv|.avi|.mp4改成mkv\|avi\|mp4

How can I do that with sed?我怎么能用 sed 做到这一点? Or maybe an easier alternative?或者也许是一个更简单的选择?

No need for sed ;不需要sed bash has basic substitution operators built in. The basic syntax for a replace-all operation is ${variable//pattern/replacement} , but unfortunately it can't be nested so you need a helper variable. bash内置了基本的替换运算符。全部替换操作的基本语法是${variable//pattern/replacement} ,但不幸的是它不能嵌套,所以你需要一个辅助变量。 For clarity, I'll even use two:为了清楚起见,我什至会使用两个:

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"`

If your find supports it, you could also consider using a different -regextype (see find -regextype help ) so you don't need quite so many backslashes anymore.如果您的find支持它,您还可以考虑使用不同的-regextype (请参阅find -regextype help ),这样您就不再需要那么多反斜杠了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM