Home > Back-end >  Find and rename double quotes contains files in directory
Find and rename double quotes contains files in directory

Time:01-17

I'm trying to rename files contains double quotes with file name in directory.

/tables/ddl/ directory

"user".sql
"customer".sql
inventory.sql
"orders".sql

Would like to remove double quotes in file names which contains that. Like this:

user.sql
customer.sql
inventory .sql
orders.sql

In my shell script, To find the files with double quotes i used find command with regax as follows. It shows list of files with double quotes.

find . -name '*["]*'

Also i tried fo relaying directory and rename files.

for myfile in /tables/ddl/*; do
    echo $myfile
    rename 's,^[0-9]{2}\.,,' *sql
done

Is that possible to at the same time find and rename files contains with double quotes?

CodePudding user response:

Judging from the usage of the rename command in the second code, you seem to have the perl-based rename command available. (There are two different rename commands, one is perl-based, the other is not. Confusing.)
Then you can rename the files removing the double quotes just with:

rename 's/"//g' /tables/ddl/*.sql
  • The first argument s/"//g is a perl statement which removes the double quotes.
  • You can pass multiple files using the type-glob *.sql to the rename command at once.
  • The command above does not affect the files which do not include double quotes.

[Edit]
Here is an alternative without the perl-based rename command:

find tables/ddl -type f -name '*"*' -print0 | while IFS= read -r -d '' file; do
    mv -- "$file" "$(sed 's/"//g' <<< "$file")"
done
  • The usage of find command is almost same as yours.
  • The -print0 option specifies a null character (\0) as a delimiter of files to protect blank characters (whitespace, tab, etc.) in the filenames, if any.
  • The -d "" option to read command corresponds to -print0 above to split the input stream on null characters into filenames back again.
  • The sed 's/"//g' <<< "$file" command removes double quotes from the filename.
  • The command above assumes the directory name (tables/ddl here) does not include double quotes.

Or simply:

for file in tables/ddl/'"'*'"'.sql; do
    mv -- "$file" "$(sed 's/"//g' <<< "$file")"
done

The single quotes around the double quotes avoid the internal asterisk * to be wrapped with the double quotes.

  •  Tags:  
  • Related