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
:~/Desktop$ rename ‘s/map/mapping/’ memory_map.c

:~/Desktop$ 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’

Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Content Management System - CMS Core Kernel C Programs Development Environment Setup Errors & Failures File Systems git Go Language Programs Hardware Platforms Home HTML JAVA Programs Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded
Tags: ,

Leave a Reply