Rom
Rom

Reputation: 225

Bash - Rename file that have " in it

Ok I have a function that will have as parameter a string and it will output a new string that doesn't have any spaces, ', "

function rename_file() {

local string_to_change=$1
local length=${#string_to_change}
local i=0   
local new_string=" "
local charac

for i in $(seq $length); do
    i=$((i-1))
    charac="${string_to_change:i:1}"

    if [ "$charac" != " " ] && [ "$charac" != "'" ] && [ "$charac" != """ ];  then #Here if the char is not" ", " ' ", or " " ", we will add this char to our current new_string and else, we do nothing

        new_string=$new_string$charac #simply append the "normal" char to new_string

    fi

done

echo $new_string #Just print the new string without spaces and other characters
}

But I just can't test if the char is " because it just doesn't work. And if I call my function with

rename_file (file"n am_e)

it just open > and waits for me to enter something.. any help ?

Upvotes: 3

Views: 76

Answers (1)

Barmar
Barmar

Reputation: 780974

Put the name in single quotes.

rename_file 'file"n am_e'

And if you want to test single quotes, put it in double quotes:

rename_file "file'n am_e"

To test both, put them in double quotes and escape the inner double quotes:

rename_file "file'na \"me"

Another option is to use a variable:

quote='"'
rename_file "file'na ${quote}me"

Also, you don't need to put parentheses around the arguments to a shell function. They're called like ordinary commands, with arguments separated by spaces on the same command line.

And you don't need that loop to replace characters.

new_string=${string_to_change//[\"\' ]/}

See Parameter Expansion in the Bash Manual for an explanation of this syntax.

Upvotes: 5

Related Questions