Skip to content
Advertisement

Linux shell script to find and rename files to remove suffix?

I have some files named like this:

file1.c.keep.apple

file2.c.keep.apple

I am trying to write a shell script so that I pass in the suffix as an argument (in this case, apple) and it will rename all of the files removing the .keep.apple.

Example execution:

script.sh apple

results in the files above being renamed to

file1.c

file2.c

So far, I have

 #! /bin/sh
 find . -type f -name '*.keep.$1' -print0 | xargs -0 rename 's/(.keep.*)$//'

and the files do not get renamed. I know the find portion is correct. I am thinking the regex on my rename is wrong. How can I get the script working the way I want?

Advertisement

Answer

Updated, try this perhaps:

#!/bin/bash

SUFFIX=$1;

find . -type f -name "*keep.${SUFFIX}" | while read -r file;
do 
    nfile=`echo $file | sed "s/.keep.${SUFFIX}//g"`; 
    mv "$file" "$nfile" 2>/dev/null; 
done

here it is running:

jgalley@jgalley-debian:/test5$ cat replace.sh 
#!/bin/bash

SUFFIX=$1;

find . -type f -name "*keep.${SUFFIX}" | while read -r file;
do 
    nfile=`echo $file | sed "s/.keep.${SUFFIX}//g"`; 
    mv "$file" "$nfile" 2>/dev/null; 
done
jgalley@jgalley-debian:/test5$ find .
.
./-filewithadash.keep.apple
./dir1
./dir1/file
./dir1/file2.keep.orange
./dir2
./dir2/file2
./file with spaces
./file.keep.orange
./file.keep.somethingelse.apple
./file.orange
./replace.sh
jgalley@jgalley-debian:/test5$ ./replace.sh apple
jgalley@jgalley-debian:/test5$ find .
.
./-filewithadash
./dir1
./dir1/file
./dir1/file2.keep.orange
./dir2
./dir2/file2
./file with spaces
./file.keep.orange
./file.keep.somethingelse.apple
./file.orange
./replace.sh
jgalley@jgalley-debian:/test5$ 
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement