Michael Mullin
Michael Mullin

Reputation: 83

How can I rename numbered files

I have 70ish shell scripts, named 1.man-pages.sh, 2.tcl.sh, 3.expect.sh etc.

I have made a mistake and need to rename these files by adding 1 to the number (eg 1.man-pages.sh => 2.man-pages.sh, 3.tcl.sh 4.expect.sh).

It's rather tedious to mv these each by hand. Does anyone have a suggestion for a bash one liner?

Upvotes: 1

Views: 71

Answers (2)

Diego Torres Milano
Diego Torres Milano

Reputation: 69208

Not a onle-liner but close...

IFS=$'\n'
for f in $(printf '%s\n' [0-9]* | sort -rnt '.' -k1); do
    mv "$f" "$(( ${f%%.*}+1 )).${f#*.}"
done

Upvotes: 3

Grigor Poghosyan
Grigor Poghosyan

Reputation: 336

for file in *.sh; do
  number=$(cut -d '.' -f1 <<< $file)
  name=$(cut -d '.' -f2 <<< $file)
  extensiton=$(cut -d '.' -f3 <<< $file)
  re='^[0-9]+$' 
  if [[ $number =~ $re ]]; then
    mv $file "$(($number + 1)).$name.$extensiton"
  fi
done

Upvotes: 0

Related Questions