Search code examples
regexshellawkrenamefile-rename

awk to update filename in directory


In the below I am trying to use awk to change part of a pair of filenames (between the hyphen and underscore) in a directory with a value stored in a variable. The below does execute but the filenames do not change. Thank you :).

variable

id=aaaaa

files in directory

00-0000-xxx-y-zzz_x1_y.txt
00-0000-xxx-y-zzz_x2_y.txt

desired

00-0000-xxx-y-aaaaa_x1_y.txt
00-0000-xxx-y-aaaaa_x2_y.txt

awk

awk -F'-' var=$id'{sub("$5","var")}1' *.txt

Solution

  • awk is changing file content, not the file name itself.

    Instead of awk, you may use rename perl utility like this:

    id='aaaaa'
    rename -n "s/^(.*)-[^_]+_/\$1-${id}_/" *.txt
    
    '00-0000-xxx-y-zzz_x1_y.txt' would be renamed to '00-0000-xxx-y-aaaaa_x1_y.txt'