Friday, March 27, 2015

sed - Unix: Search and replace in file names


Using sed, I can search and replace text in a file. Is there a way I can do search and replace of filenames? For example if I have a bunch of files in a folder with names like these:



  • foo01

  • foo02

  • bar001

  • bar002


I would like to quickly rename all of the ones starting with foo so that they have 3 digits instead of 2.


Answer



#!/bin/bash
shopt -s nullglob
for file in foo*
do
filename=${file%%[0-9]*}
num=${file##*[^0-9]}
newnum=$(printf "%03d" $num)
newfile=${filename}${newnum}
mv "$file" "$newfile"
done

No comments:

Post a Comment

linux - How to SSH to ec2 instance in VPC private subnet via NAT server

I have created a VPC in aws with a public subnet and a private subnet. The private subnet does not have direct access to external network. S...