I have some files in my current directory whose file-name is of this pattern:
Related posts:
- Padding zeros in filename using Bash in UNIX
- Rename file to uppercase except extension - Bash
- Rename multiple files using UNIX rename command
$ ls -1
log.1024.94.1326776200.1326776300.172.16.12.6.1326844995.0.s-1326528000.r-8192.txt
log.1024.94.1326776400.1326776400.172.16.12.5.1326844995.0.s-1326528000.r-2234.txt
log.1024.95.1326776420.1326776460.172.16.12.5.1326844995.0.s-1326528000.r-8192.txt
Requirement: Append a text "MY-2" as the 6th field (dot delimited) of the filename. E.g.
log.1024.94.1326776200.1326776300.172.16.12.6.1326844995.0.s-1326528000.r-8192.txtshould be renamed to
log.1024.94.1326776200.1326776300.MY-2.172.16.12.6.1326844995.0.s-1326528000.r-8192.txt
A bash script using awk to achieve this:
for file in $(ls) do newfilename=$(echo $file | awk 'BEGIN {FS=OFS="."} {$6="MY-2" OFS $6} {print}') mv -v $file $newfilename doneAll the files are renamed to:
$ ls -1 log.1024.94.1326776200.1326776300.MY-2.172.16.12.6.1326844995.0.s-1326528000.r-8192.txt log.1024.94.1326776400.1326776400.MY-2.172.16.12.5.1326844995.0.s-1326528000.r-2234.txt log.1024.95.1326776420.1326776460.MY-2.172.16.12.5.1326844995.0.s-1326528000.r-8192.txtFeel free to post (as comment below) any alternative to this, much appreciated and a big thank you in advance.
Related posts:
- Padding zeros in filename using Bash in UNIX
- Rename file to uppercase except extension - Bash
- Rename multiple files using UNIX rename command
4 comments:
Don't parse ls '$(ls)' since users can put odd characters in a file name you might not get what you expect when you use ls' output.
for file in log*.txt; do
....
done
@Derek Schrock, makes sense, thanks a lot.
Also, I prefer the following which works for large set of files for which commands like 'ls' fails with 'argument list too long', we have other alternatives to handle 'argument list too long' though.
FILES=$(echo log*.txt)
for FILE in $FILES
do
...
...
done
Sorta related: I wrote a gnarly bash script for renaming ebook files a while ago.
http://ropata.wordpress.com/2009/08/01/bash-script-filefolder-names-with-spaces-renaming-reordering-words/
If it might be a concern that the glob might result in "argument list too long", then we can resort to either the find or the xargs commands.
find . -type f -name \*.txt -maxdepth 1 -exec sh -c '_n=`sed -e "s/[.]/&\\n/5;s/[.]\\n/.MY-2./"`;
mv "$1" "$_n";' {} {} \;
Post a Comment