Reputation: 171
I have a folder on OSX with TV programs downloaded from an online DVR. I want to make a list of the programs and format it to match another list for comparison.
When I run the following command in shell, everything works fine and I get the list I want.
ls *.mp4 > loaded_shows.txt
sed -i$0 's/\(.*\)_/\1\ /' loaded_shows.txt
sed -i$0 's/\(.*\)_/\1\ /' loaded_shows.txt
sed -i$0 's/\(.*\)_/\1\ /' loaded_shows.txt
cat loaded_shows.txt
When I put the same commands into a bash script, sed gives the following error message for each of the in-place replacement even though the script is in the same directory as the files are.
sed: rename(): No such file or directory
And for completeness, here's the bash script:
#!/bin/bash
ls *.mp4 > loaded_shows.txt
sed -i$0 's/\(.*\)_/\1\ /' loaded_shows.txt # replace last _ with space
sed -i$0 's/\(.*\)_/\1\ /' loaded_shows.txt # again replace last _ with space
sed -i$0 's/\(.*\)_/\1\ /' loaded_shows.txt # remove the file extension
cat loaded_shows.txt
And sample input filenames:
666_Park_Avenue_2014-04-22_23.35.mp4
Americans_2014-04-20_22.45.mp4
Scandal_2014-04-20_21.00.mp4
The_Voice_of_USA_2014-04-22_19.30.mp4
How can I get sed to work in the bash script?
Upvotes: 4
Views: 2733
Reputation: 46856
You've already noted your error with sed's -i
option. Well done for finding it. :)
If the comments in your script are an indication of what you're trying to achieve, I'd actually refactor the script to use sed in a pipe, just once, looking something like this:
#!/bin/bash
for f in *.mp4; do
echo "$f" | sed 's/_\([^_]*\)_\([^_]*\).mp4$/ \1 \2/'
done > loaded_shows.txt
Running sed fewer times is more economical, and opening/closing your text file only once is lots more economical. Because, you know, a millisecond wasted is a millisecond lost.
I should point out the for
loop here. Generally, when you're running through lists of files in a shell script, you want to use for
rather than parsing the output of ls
. Parsing ls is a well known gotcha in the world of shell scripting, and it's best not to allow yourself bad habits like that, even in small scripts in controlled environments.
Upvotes: 0