0

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, i.e. change .mkv|.avi|.mp4 to mkv\|avi\|mp4

How can I do that with sed ? Or maybe an easier alternative ?

3
  • 3
    Please add a shebang and then paste your script at shellcheck.net and try to implement the recommendations made there. Commented Feb 21, 2021 at 11:51
  • 2
    I'd do files=( "$DIR"/*.{mkv,avi,mp4} ) instead. Storing find's output in a scalar variable is not a good idea, especially when there is no need to use it at all. Commented Feb 21, 2021 at 12:36
  • @oguzismail is it better to use ls in a variable ? Commented Feb 21, 2021 at 14:25

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.