I would like to use sed to delete and replace some characters in a bash script.
#!/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
How can I do that with sed? Or maybe an easier alternative?
No need for 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.