bash - Renaming files with multiple variables in the file names -
i have multiple files format: this-is-text_r_123.txt
, this-is-text.txt
.
what (preferable using for
loop) rename this-is-text.txt
files corresponding this-is-text_r_123.txt
matches have i
instead of r
in file name. considering this-is-text
random text (different 1 file another) , 123
in example above combination of 3 numbers. files in 1 directory.
i tried mv
, rename
wasn't successful
i've searched , reviewed file renaming questions here none matched case
i changed technology python demonstrate how in language more convenient bash:
#!/usr/bin/python3 import glob import re text_files = glob.glob('*.txt') #divide files 2 groups: "normal" files without _r , "target" files _r normal_files = {} target_files = {} path in text_files: #extract "key" (meaning part of file name without _r or _i) #as whether file contains _r or _i, or not #using regular expressions: result = re.match('(?p<key>.*?)(?p<target>_[ri]_?\d*)?\..*$', path) if result: if result.group('target'): target_files[result.group('key')] = path else: normal_files[result.group('key')] = path print(normal_files) print(target_files) #now figure out how rename files using built dictionaries: key, path in normal_files.items(): if key in target_files: target_path = target_files[key].replace('_r', '_i') print('renaming %s %s' % (path, target_path))
for following set of files:
asd.txt asd_r_1.txt test test.txt test test_r2.txt test_i_1.txt
this script produce:
{'test test': 'test test.txt', 'asd': 'asd.txt'} {'test test': 'test test_r2.txt', 'another test': 'another test_i_1.txt', 'asd': 'asd_r_1.txt'} renaming test test.txt test test_i2.txt renaming asd.txt asd_i_1.txt
you should able move files this.
as see, it works.
if really need doing in bash, should easy port using sed
or awk
.
Comments
Post a Comment