IN-Decent

Re-decentralizing internet with free software

Bulk Rename Files With Standard GNU Tools

Posted at — Jul 23, 2021

Bulk rename files present in multiple subpaths using tools find, sed and xargs which is available by default on all GNU/Linux systems.

This is accomplished by tools mentioned above using below pipeline,

find . -maxdepth N -type f -name "$match_pattern" -print0 | \
sed -ze 'p' -E -e "s/$old_pattern/$new_pattern/g"  | \
xargs -0 -n2 mv

Explanation of the options used in above pipeline:

1. find find files to rename
. will start the search from the current path
-maxdepth N only look in N directory levels below current path
-type f list only files
-name "$pattern" filter and list only files matching given shell pattern
-print 0 print output lines as NULL terminated instead of default new-line
2. sed to print both old filename and new filenames to pass to mv command
-z treat lines as NULL terminated
-e to combine multiple sed commands
'p' print same input as output for old filename
-E support extended regular expressions
"s/old/new/g" replace old text with new text multiple times in filename for use as new file name
3.xargs to invoke mv multiple times for each file
-0 treat input as NULL terminated as output by sed
-n2 pass only atmost 2 arguments for each mv command i.e mv old_name new_name

To support filenames with spaces, quotes, backslash chars like newlines, we use NULL char as line terminator in all pipeline commands. Without this rename will fail if filenames contain spaces, quotes and other chars that are treated differently by shell.

NOTE:

NULL termination support is available on GNU implementation, but may not be implemented on other unix implementations.

References:

  1. stackoverflow.com