ChrisW
ChrisW

Reputation: 5068

Renaming files in a loop

I have a list of files: File_2011_1.txt, File_2011_2.txt, File_2011_3.txt ... File_2011_100.txt; I want to update 2011 to 2012 in all the file names.

The following doesn't work:

for FILES in `ls`; do NEWNAME=`echo ${FILES} | sed -e 's/*2011*/*2012*/'`; echo ${FILES} ${NEWNAME}; done;

but this does:

for FILES in `ls`; do NEWNAME=`echo ${FILES} | sed -e 's/File_2011*/File_2012*/'`; echo ${FILES} ${NEWNAME}; done;

So, why does a wildcard in before the part of the filename I want to change not work?

Upvotes: 0

Views: 127

Answers (1)

osgx
osgx

Reputation: 94175

Because sed uses not a File willcard (like it was in bash or DOS), but regex (regular expressions).

You can do just sed -e 's/2011/2012/' (by default 's' command of sed matches part of string). Wildcard * will be written as .* in regex language.

Basic rules of sed regexps:

  • The caret (^) matches the beginning of the line.
  • The dollar sign ($) matches the end of the line.
  • The asterisk (*) matches zero or more occurrences of the previous character.
  • The dot (.) matches any character.
  • The [ and ] are used to match set of characters, e.g. [a-c01] matches with single char any of: a, b, c, 0, or 1.

Upvotes: 5

Related Questions