Fallenreaper
Fallenreaper

Reputation: 10704

Bulk Renaming Files isnt working for me

I am running a shell script on my mac, and i am getting a "No Such file or directory.

The input is: the replacement_name, and the working dir. The output is: changing all files in the directory from $file to $newfilename

#!/bin/sh

echo "-------------------------------------------------"
echo "Arguments:"
echo "Old File String: $1"
echo "New File Name Head: $2"
echo "Directory to Change: $3"
echo "-------------------------------------------------"
oldname="$1"
newname="$2"
abspath="$3"
echo "Updating all files in '$abspath' to $newname.{extension}"

for file in $(ls $abspath);
do
    echo $file
    echo $file | sed -e "s/$oldname/$newname/g"
    newfilename=$("echo $file| sed -e \"s/$oldname/$newname/g\"")
    echo "NEW FILE: $newfilename"
    mv $abspath/$file $abspath/$newfilename
done

It seems that it doesnt like assigning the result of my 1-liner to a variable.

old_filename_string_template.dart
test_template.dart
./bulk_rename.sh: line 16: echo old_filename_string.dart| sed -e "s/old_filename_string/test/g": No such file or directory
NEW FILE: 

Test Information:

 mkdir /_temp_folder
 touch old_filename_string_template.a  old_filename_string_template.b  old_filename_string_template.c old_filename_string1_template.a  old_filename_string1_template.b  old_filename_string1_template.c old_filename_string3_template.a  old_filename_string3_template.b  old_filename_string3_template.c
./convert.sh old_filename_string helloworld /_temp_folder

Upvotes: 0

Views: 47

Answers (2)

Bach Lien
Bach Lien

Reputation: 1060

Try to put double quotes outside backticks/subtitutions (not INSIDE backticks/substitutions like $("..."))

newfilename="$(....)"

By the way, please consider to use the package perl rename which already does this bulk file rename very well, with Perl regex style which is easier to use. This perl rename command maybe alreay available in your (Mac) distro. See intro pages.

Upvotes: 0

tripleee
tripleee

Reputation: 189417

The double quotes here make the shell look for a command whose name (filename, alias, or function name) is the entire string between the quotes. Obviously, no such command exists.

> newfilename=$("echo $file| sed -e \"s/old_filename_string/$1/g\"")

Removing the double quotes inside the parentheses and the backslashes before the remaining ones will fix this particular error.

The construct $(command sequence) is called a command substitution; the shell effectively replaces this string with the standard output obtained by evaluating command sequence in a subshell.

Most of the rest of your script has much too few quotes; so it's really unclear why you added them here in particular. http://shellcheck.net/ is a useful service which will point out a few dozen more trivial errors. Briefly, anything which contains a file name should be between double quotes.

Upvotes: 2

Related Questions