Search code examples
bashdosbatch-rename

Batch renaming replace with part of the original file name DOS and Bash


I know this has been covered many times, but i still can't seem to get a good solution to this particular aspect. I have the same problem in both bash and DOS. I have a file of many .csv files named abcYYMMDDf.csv and I want to change the file name to the YYMMDD part which corresponds to the date it was created. Note the "f" after the YYMMDD, so really i would like an equivalent of excel's mid() to take the middle date.

In bash I understand the rename function, and the * wildcard I tried variations on

rename abc*f.csv *.csv abc*

thinking that the * would stand in for YYMMDD but obviously it didn't. I saw another method involving selecting s/([a-z]*) but that would just take the whole file name surely?

In DOS I tried

ren abc*f.csv *.csv

Solution

  • Bash parameter expansion can be used to strip the 'abc' and the 'f' in two steps, using prefix removal and pattern substitution, respectively.

    for f in abc*f.csv; do
        new_f=${f#abc}
        new_f=${new_f/%f.csv/.csv}
        mv $f $new_f
    done
    

    You could use sed in place of parameter expansion to remove 'abc' and 'f' in one step:

    for f in abc*f.csv; do
        new_f=$(echo $f | sed 's/abc\(.*\)f/\1/')
        mv $f $new_f
    done
    

    I cannot answer the DOS version; you may be better off asking that in a separate question.