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).

Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227
nish
  • 283
  • 1
  • 3
  • 12
  • 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 '14 at 10:21
  • 1
    It's a duplicate of [Batch renaming files](http://unix.stackexchange.com/q/1136/22222) – X Tian Feb 11 '14 at 11:59

2 Answers2

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.

slm
  • 363,520
  • 117
  • 767
  • 871
  • This is a useful command. You could merge it into @terdon's answer above. – Faheem Mitha Feb 11 '14 at 08: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 '14 at 12:06
  • @nish - there are 2 different implementations of `rename`. Which distro is this? – slm Feb 11 '14 at 12:55
  • CentOS release 6.5 (Final) – nish Feb 13 '14 at 07:14
  • @nish - OK so the example I showed you will work then, that's the CentOS/Fedora version as well. – slm Feb 13 '14 at 07: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*

rralcala
  • 91
  • 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 '14 at 13:51
  • 1
    Also, there's no need to spawn a `sed` instance for each file to be renamed. Either [use `rename`](http://unix.stackexchange.com/a/114693/28235) 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 '14 at 14:00