1

I've looked around for a one line solution ( as bash offers ) to replace part of filename.

Given that a folder has image sequence like

ve2_sq021_sc001_v000.0101.jpg
ve2_sq021_sc001_v000.0102.jpg
ve2_sq021_sc001_v000.0103.jpg
ve2_sq021_sc001_v000.0104.jpg

Need to replace only v000 with v09 ( say ). How is it possible (throughout directory).

2
  • while if i know that it is v000 in fourth position then i can do as suggested. My question is - How is it possible to go to fourth location after _ and replace that with "v09". Can regular expression come useful here.
    – nish
    Feb 11, 2014 at 10:21
  • 1
    It's a duplicate of Batch renaming files
    – X Tian
    Feb 11, 2014 at 11:59

2 Answers 2

3

If you have the unix command rename installed you can do this trivially like this:

$ rename v000 v09 *.jpg

$ ls -1
ve2_sq021_sc001_v09.0101.jpg
ve2_sq021_sc001_v09.0102.jpg
ve2_sq021_sc001_v09.0103.jpg
ve2_sq021_sc001_v09.0104.jpg

NOTE: This is using the rename implementation that's included with the package util-linux.

5
  • This is a useful command. You could merge it into @terdon's answer above. Feb 11, 2014 at 8:55
  • ok. This may be silly to ask. how will replace in a path in script. pth="/tmp/images" rename v000 v09 $pth/*.jpg this does not work. Error is "No such file or directory"
    – nish
    Feb 11, 2014 at 12:06
  • @nish - there are 2 different implementations of rename. Which distro is this?
    – slm
    Feb 11, 2014 at 12:55
  • CentOS release 6.5 (Final)
    – nish
    Feb 13, 2014 at 7:14
  • @nish - OK so the example I showed you will work then, that's the CentOS/Fedora version as well.
    – slm
    Feb 13, 2014 at 7:16
1
for f in $(ls ve2*); do mv $f $(echo $f | sed s/v000/v09/g ); done

If you want to make it recursive, you could use find instead of ls ve2*

2
  • 1
    Do not ever parse the output of ls. You'll be sorry for it the instant you encounter a filename or path containing whitespace. Instead, use the globbing of you shell (for f in ve2*; do) or find's -exec parameter.
    – n.st
    Feb 11, 2014 at 13:51
  • 1
    Also, there's no need to spawn a sed instance for each file to be renamed. Either use rename or at least let bash handle the strong replacement: ${f//v000/v09} evaluates to the value of f with all occurrences of 'v000' replaced by 'v09'.
    – n.st
    Feb 11, 2014 at 14:00

Not the answer you're looking for? Browse other questions tagged .