How to rename part of a filename and replace the string in those files

If we want to rename only certain part of the filename, for example, we want to change a filename “memory_map.c” to “memory_mapping.c” i.e. we just want to rename “map” to “mapping” of the file, we  can use following command,

$ ls -al memory_map.c
       -rw-rw-r-- 1 user user 642 Aug 19 22:53 memory_map.c 
 $ rename 's/map/mapping/' memory_map.c
 $ ls -al memory_mapping.c
      -rw-rw-r-- 1 user user 642 Aug 19 22:53 memory_mapping.c

So, using above command, we change only part of filename from “map” to “mapping”. Now, we can just replace filename with “*.c” or “*” to rename all the files in the particular directory.

Now, if we want to change some string like function name in the same file or number of other files, we can use sed to do this in a single command as,

$ grep -rl somestring memory_mapping.c | xargs sed -i 's/somestring/string2/g'

for changing “somestring” from multiple files, use command,

$ grep -rl somestring "/directory" | xargs sed -i 's/somestring/string2/g'

Leave a Comment