UNIX - Sed command to rename multiple files in a folder by replacing a substring in the file name.

 Requirement - Folder has multiple .csv files starting with Knowstar.

For ex - Knowstar_V1_1.csv

             Knowstar_V1_2.csv  

We need to rename the files as below -

Knowstar_V1_1.csv to Knowstar_1.csv

Knowstar_V1_2.csv to Knowstar_2.csv

This can be achieved by replacing the '_V1_' in the original filenames with a single underscore '_'.

The below single line command will rename all the files starting with Knowstar according to our requirements.

for f in Knowstar_*.csv; do mv "$f" $(echo "$f" | sed 's/_V1_/_/'); done

The for loop cycles through all the files matching the name pattern Knowstar* in the directory.

The s (sed 's/_V1_/_/') command in sed means substitute.

The next argument is the substring/pattern to be found and replaced (sed 's/_V1_/_/') . In our example, it is '_V1_'

The last argument is the substring that needs to be replaced in place of the old substring. (sed 's/_V1_/_/'). In our example, it is '_'.

This can be directly executed through the Unix command line or executed as part of a script.


1 Comments

Previous Post Next Post

Contact Form