Sedname - Batch rename files using sed

Renaming files using sed is nothing new, but this script makes the process a little more friendly and adds a few features, including insertion of sequential numbers and a simulation mode.  The output of any find command can also be piped through sedname.
sedname version 1.0.0
Batch-renames files using a sed script
Usage: sedname [OPTIONS] SEDSCRIPT FILE ...
Usage: find [...] | sedname [OPTIONS] SEDSCRIPT
Example: sedname 's/\(.*\)\.jpg/\1.jpeg/' *.jpg
Example: find /mypics | sedname 's/\(.*\)\.jpg/\1.jpeg/'
OPTIONS:
--sim simulate only
--dir rename directories too
Use #D to insert a number with D digits forming a unique filename
Example: sedname 's/thisname.*/thatname#3/' *
( changes thisname* to thatname001, thatname002, ... )
Use #0 in replacement name to insert a number if needed
Example: sedname 's/thisname.*/thatname#0/' *
( changes thisname* to thatname, thatname1, thatname2, ... )
http://igurublog.wordpress.com/download … t-sedname/
http://aur.archlinux.org/packages.php?ID=37707

What does it have over zsh's zmv:
# Remove illegal characters in a fat32 file system. Illegal characters are
# / : ; * ? " < > |
# NOTE: ``-Q'' and (D) is to include hidden files.
$ unwanted='[:;*?\"<>|]'
$ zmv -Q "(**/)(*$~unwanted*)(D)" '$1${2//$~unwanted/}'
# Changing part of a filename (i. e. "file-hell.name" -> "file-heaven.name")
$ zmv '(*)hell(*)' '${1}heaven${2}'
# or
$ zmv '*' '$f:s/hell/heaven/'
# remove round bracket within filenames
# i. e. foo-(bar).avi -> foo-bar.avi
$ zmv '*' '${f//[()]/}'
# serially all files (foo.foo > 1.foo, fnord.foo > 2.foo, ..)
$ ls *
1.c asd.foo bla.foo fnord.foo foo.fnord foo.foo
$ c=1 zmv '*.foo' '$((c++)).foo'
$ ls *
1.c 1.foo 2.foo 3.foo 4.foo foo.fnord
# Rename "file.with.many.dots.txt" by substituting dots (exept for the last
# one!) with a space
$ touch {1..20}-file.with.many.dots.txt
$ zmv '(*.*)(.*)' '${1//./ }$2'
# Remove the first 4 chars from a filename
$ zmv -n '*' '$f[5,-1]' # NOTE: The "5" is NOT a mistake in writing!
# Rename names of all files under the current Dir to lower case, but keep
# dirnames as-is.
$ zmv -Qv '(**/)(*)(.D)' '$1${(L)2}'
# replace all 4th character, which is "1", with "2" and so on
$ zmv '(???)1(???[1-4].txt)' '${1}2${2}'
# Remove the first 15 characters from a string
$ touch 111111111111111{a-z}
$ zmv '*' '$f[16,-1]'
# Replace spaces (any number of them) with a single dash in file names
$ zmv -n '(**/)(* *)' '$1${2//( #-## #| ##)/-}'
# or - with Bash
$ find . -depth -name '* *' -exec bash -c '
> shopt -s extglob
> file=$1
> dir=${file%/*}
> name=${file##*/}
> newname=${name//*([ -]) *([ -])/-}
> mv -i -- "$file" "$Dir/$newname"' {} {} \;
# Clean up file names and remove special characters
$ zmv -n '(**/)(*)' '$1${2//[^A-Za-z0-9._]/_}'
# Add *.py to a bunch of python scripts in a directory (some of them end
# in *.py and give them all a proper extension
$ zmv -n '(**/)(con*)(#qe,file $REPLY | grep "python script",)' '$1$2.py'
# lowercase all extensions (i. e. *.JPG) incl. subfolders
$ zmv '(**/)(*).(#i)jpg' '$1$2.jpg'
# Or - without Zsh
$ find Dir -name '*.[jJ][pP][gG]' -print | while read f
> do
> case $f in
> *.jpg) ;
> *) mv "$f" "${f%.*}.jpg" ;
> esac
> done
# remove leading zeros from file extension
$ ls
filename.001 filename.003 filename.005 filename.007 filename.009
filename.002 filename.004 filename.006 filename.008 filename.010
$ zmv '(filename.)0##(?*)' '$1$2'
$ ls
filename.1 filename.10 filename.2 filename.3 filename.4 filename.5 ..
# renumber files.
$ ls *
foo_10.jpg foo_2.jpg foo_3.jpg foo_4.jpg foo_5.jpg foo_6.jpg ..
$ zmv -fQ 'foo_(<0->).jpg(.nOn)' 'foo_$(($1 + 1)).jpg'
$ ls *
foo_10.jpg foo_11.jpg foo_3.jpg foo_4.jpg foo_5.jpg ...
# adding leading zeros to a filename (1.jpg -> 001.jpg, ..
$ zmv '(<1->).jpg' '${(l:3::0:)1}.jpg'
# See above, but now only files with a filename >= 30 chars
$ c=1 zmv "${(l:30-4::?:)}*.foo" '$((c++)).foo'
# Replace spaces in filenames with a underline
$ zmv '* *' '$f:gs/ /_'
# Change the suffix from *.sh to *.pl
$ zmv -W '*.sh' '*.pl'
# Add a "".txt" extension to all the files within ${HOME}
# ``-.'' is to only rename regular files or symlinks to regular files,
# ``D'' is to also rename hidden files (dotfiles))
$ zmv -Q '/home/**/*(D-.)' '$f.txt'
# Or to only rename files that don't have an extension:
$ zmv -Q '/home/**/^?*.*(D-.)' '$f.txt'
# Recursively change filenames with characters ? [ ] / = + < > ; : " , - *
$ chars='[][?=+<>;",*-]'
$ zmv '(**/)(*)' '$1${2//$~chars/%}'
# Removing single quote from filenames (recursively)
$ zmv -Q "(**/)(*'*)(D)" "\$1\${2//'/}"
# When a new file arrives (named file.txt) rename all files in order to
# get (e. g. file119.txt becomes file120.txt, file118.txt becomes
# file119.txt and so on ending with file.txt becoming file1.txt
$ zmv -fQ 'file([0-9]##).txt(On)' 'file$(($1 + 1)).txt'
# lowercase/uppercase all files/directories
$ zmv '(*)' '${(L)1}' # lowercase
$ zmv '(*)' '${(U)1}' # uppercase
# Remove the suffix *.c from all C-Files
$ zmv '(*).c' '$1'
# Uppercase only the first letter of all *.mp3 - files
$ zmv '([a-z])(*).mp3' '${(C)1}$2.mp3'
# Copy the target `README' in same directory as each `Makefile'
$ zmv -C '(**/)Makefile' '${1}README'
# Removing single quote from filenames (recursively)
$ zmv -Q "(**/)(*'*)(D)" "\$1\${2//'/}"
# Rename pic1.jpg, pic2.jpg, .. to pic0001.jpg, pic0002.jpg, ..
$ zmv 'pic(*).jpg' 'pic${(l:4::0:)1}.jpg'
$ zmv '(**/)pic(*).jpg' '$1/pic${(l:4::0:)2}.jpg' # recursively
(from zsh-lovers)
Edit: tried it now, and had to remove this silly block to make it let me use alternate delimiters:
if [ "${sedscript:0:2}" != "s/" ]; then
echo "Invalid sed script: $sedscript" > /dev/stderr
exit 1
fi
Last edited by JohannesSM64 (2010-05-31 15:29:44)

Similar Messages

  • Batch rename files on the server?

    Can someone explain how to batch rename files on the server ?
    I have 1000 rows each containing these fields
    id (unique key)
    productCode
    filename1
    filename2
    For every row I need to rename the following fields:
    Rename [filename1] to [productCode]_[id]_1
    Rename [filename2] to [productCode]_[id]_2
    also I need to rename the actual file on the server using the above scheme
    Can someone show me the way ? I'm a little rusty with ColdFusion

    So far I've got everything working apart from CFFILE which works only if it finds a corresponding jpeg file on the server. In other words it works perfectly until row 20 of the database because the filename contained in the field doesn't have a matching jpeg file on the server, so CFFILE fails like this...
    Attribute validation error for tag CFFILE.
    The value of the attribute source, which is currently C:\images\DSCN1293.JPG, is invalid.
    The error occurred in C:\Inetpub\wwwroot\link\htdocs\old_apps\psp\updater.cfm: line 63
    61 :                    action = "rename"
    62 :                    source = #my_source1#
    63 :                    destination = #my_destination1#>
    is there a way to carry on looping through the remaining rows and ignore the above fail ?

  • Batch rename files

    How can I batch rename files to original (embedded in metadata) file names?

    If you are saying that your photos have their original filename stored as the DocumentName field in the EXIF metadata, you can use the free ExifToolGUI:
    http://www.softpedia.com/get/PORTABLE-SOFTWARE/Multimedia/Graphics/Portable-ExifToolGUI.sh tml
    It requires the free ExifTool:
    http://www.softpedia.com/progDownload/ExifTool-Download-90656.html
    ExifToolGUI allows you to rename files using that DocumentName field -- just be sure the extension is included.
    Added:
    I just installed those latest versions, and there isn't the file renaming option any more.
    Can probably be done by setting up an ExifTool commandline, but I haven't experimented with that yet.
    Ken
    Message was edited by: photodrawken to add more info.

  • Rename/Batch Rename files

    I use PSE 5.
    I name all my images before I import them into Organizer. Here is an example: 2007-11-01 071500 Bolsa Chica pelican -- meaning this picture of a pelican was taken November 1, 2007 at 7:15AM. I may have a dozen or more images of pelicans from that day, but taken at different times obviously. If I would like to rename/batch rename these files to indicate brown pelicans instead of just pelicans, can I do it within the program and still retain the date and the different times for images?
    I can't find a way to do it. And I've searched this site as well as The Missing Manual. I've been using PSE since Ver. 3, but have always used another program to batch rename files. I'm guessing Adobe expects users to rely on tags, otherwise they would have a more "sophisticated" batch rename capability.
    But am I missing something about batch renaming? Sorry for the very long post . . .
    Wendell

    I have several bones to pick with PSE5's file rename ability (in Organizer, go to File, Rename), primarily the 30-character limit on new names.
    I use long file names like
    2007-11-11 Al and Nadia wedding NYC roses-1.jpg
    2007-11-11 Al and Nadia wedding NYC roses-2.jpg
    2007-11-11 Al and Nadia wedding NYC Peter and Julie.jpg
    The spaces make for easier legibility to humans.
    If I were to include these files in a web address, I'd use hyphens.
    For this past Thanksgiving I toiled over the metadata in a group photo that might become important for family history, adding title, caption, keywords, date. I found that the "Save for Web" dialog strips some or all of the metadata, and other programs might or might not read or preserve the metadata.
    A number of people who receive my photos cannot readily use the metadata:
    --Naive users (gram and gramps)
    --Busy and distracted users (the niece who is a mother of 3; the day-trader who's thinking about his puts and calls)
    --People with poor support (a friend who has some sort of Photoshop Starter edition at work that does not recognize keywords; and she can't justify even Photoshop Elements)
    Even among all these folks, almost no one is using an operating system that requires short names.
    So, I put an abundance of information into my file names. Photoshop Elements allows that ON IMPORT, but not after the fact IN THE ORGANIZER.
    I just hope that this inconsistency is fixed in PSE6. I get tired of explaining this over and over again to folks.
    -- Bob
    P.S. I love Photoshop Elements, but I'm looking into moving my picture store to my MacBook Pro, and using Bridge (already installed) and GraphicConvert to manage my photos.

  • Batch rename files preserving the original file name in metadata

    How can I batch rename files while preserving the original file name in metadata? (Don't want the old file name as part of the new file name)
    (Adobe CS Bridge can do this with some success, but I don't want to be dependant on this software. Results are inconsistent.)

    With a simple terminal script. More details needed, though.

  • Custom batch rename files with Aperture 3 in the following format: IMG_0023.cr2 to Smith_YYMMDD_0023.cr2?  I cannot find a way to structure the date in Aperture as such, as well as extract only the camera file

    Please advise how to custom batch rename files with Aperture 3 in the following format: IMG_0023.cr2 to Smith_120816_0023.cr2?  I cannot find a way to structure the date in Aperture as such (YYMMDD), as well as extract only the camera file (0023, for example).  Adobe Bridge CS5 can do this, but NONE of the Adobe software is retina optimized, and is terrible to look at.

    In Aperture you are limited to renaming files by the entries in the File Naming preset window.
    At what point are you looking to rename, import or export? It might be possible to do what you are looking to do external to Aperture either via a script or other software.
    regards

  • Rename File using ABAP

    Hi,
    Can any one help me how to rename file using ABAP programme.
    Thanks,
    ABDUR

    use these function module
    RS_RENAME_PROGRAM              Rename Program With All Dependent Objects
    RS_RENAME_PROGRAM_INCLUDE      Rename Include Progam Without Any Other Objects

  • Batch Renaming Files

    Greetings,
    Is there a way to "Batch Rename" a group of files?
    For example, I might want to rename dog.gif, cat.gif,
    rat.gif, etc. to animal01.gif, animal02.gif, animal03.gif, etc.
    Thanks,
    folsombob

    folsombob wrote:
    > I don't have a problem batch renaming files outside of
    DW. If I do, though, I
    > will break all of the links and references.
    There is no way of batch renaming files and preserving links
    and references.
    However, you can rename one file at a time in the Files
    panel, and
    Dreamweaver will automatically update the links throughout
    the site.
    David Powers, Adobe Community Expert
    Author, "Foundation PHP for Dreamweaver 8" (friends of ED)
    Author, "PHP Solutions" (friends of ED)
    http://foundationphp.com/

  • How can I Batch Rename Files in Aperture?

    Yesterday I imported some new photos and accidentally used the settings from my last import which named my images in a way that needs to be changed. I have already rated and edited many of the images so I don't want to reimport them from my memory cards.
    Is there a way to batch rename the images - preferably to the original file name from the camera? If not a custom name would be fine.

    Metadata->Batch Change

  • Rename files using text or excel file

    I am trying to find out how to rename files on my pc using the names stored in a text document
    eg. the file on the pc is called "C07_08.dat"
    the text file has the following line "3am Eternal         KLF         03:15 121 BMG         C07.08"
    i want to change the name of the file "C07_08.dat" to "3am Eternal.mpeg"
    What I would like is a batch file or program or something that will see the text "C07.08" and find the corresponding file "C07_08.dat" and rename it "3am Eternal.mpeg"
    I have managed to create a excel document that has the information in four separate columns
    Column A has the name of the file I want to use (ie. 3am Eternal) Column B & C have unneeded information and Column D has the file reference (ie. C07.08)
    I was told that Python or Visual basic could do this so I downloaded them but I have no experience with this so im lost as to what to do, I have over 1800 of these files so doing it file by file will take quite a while.
    I have included a sample of the text file for reference if that helps
    3am Eternal KLF 03:15 121 BMG C07.08
    4 In The Morning Gwen Stefani 04:22 092 UMA HD1.10
    4 Minutes Madonna ft J Timberlake 04:04 113 WAR HE3.05
    5 6 7 8 Steps 03:24 000 BMG C48.03
    5678 Steps 03:23 140 MUS H16.02
    6 Of 1 Thing Craig David 03:15 116 WAR HE2.11
    60 MPH New Order 03:51 125 WAR N57.11
    7 Days Craig David 04:30 084 SHO N41.16
    7 Things Miley Cyrus 03:29 107 EMI HE7.09
    99 Luft Balloons Nena 03:58 095 WAR C27.10
    99 Times Kate Voegele 03:27 112 UMA HG6.07
    A Girl Like You Edwyn Collins 03:47 126 MDS R06.08
    A Little Bit Pandora 03:35 132 UMA H23.01
    A Little Less Conversation Elvis VS JXL 03:02 115 BMG H68.03
    A Matter Of Trust Billy Joel 04:00 110 SON C59.11
    A New Day Has Come Celine Dion 04:20 092 SON H65.20
    A Woman Like You Mondo Rock 04:03 169 MUS R06.01
    About You Now Sugababes 03:32 083 UMA HD5.08
    Absolutely Everybody Vanessa Amorosi 03:52 124 TRA H40.06
    Absolutely Fabulous Pet Shop Boys 03:45 132 EMI C15.02
    Accidentally In Love Counting Crows 03:08 138 UMA H94.05
    According To You Orianthi 03:18 066 UMA HG4.12
    Achy Breaky Heart Billy Ray Cyrus 03:55 122 SON K11.02

    Here are two VBScripts that will rename the files based on the text file example you provided. The script that reads a
    TEXT FILE requires each entry to be separated by
    ONE TAB  because it is the
    TAB
    that it uses to split each line into 4 parts (part1 - old file name, part2 and part3 - items you don’t need, part 4 - new file name). If there is more that one tab then the Split Function will not work properly.
    The second VBScript will read the
    EXCEL FILE row by row and use the values in Column A for the old file name and
    Column D for the new file name. This approach will work much better if you have an excel document setup like this.
    I used your example that you provided and it test fine for both approaches.
    'Read text file
    Dim objFSO, objFolder, inFile, strInLine, strOldFile, strNewFile
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'Select the folder
    Set objFolder = objFSO.GetFolder("C:\Scripts\MusicFiles")
    'Open Text File
    Set inFile = objFSO.OpenTextFile("C:\Scripts\MusicFiles.txt",1)
    Do Until inFile.AtEndOfStream
    'Read text file line by line and Split each line into 4 parts.
    strInLine = Split(inFile.ReadLine, vbTab)
    'Old File name
    strOldFile = strInLine(3)
    'new File name
    strNewFile = strInLine(0)
    'Loop through the files in the folder
    For Each File In objFolder.Files
    'If the file name matches the old file name above
    If File.Name = strOldFile & ".dat" Then
    'Replace it
    File.Name = strNewFile & ".mpeg"
    End If
    Next
    Loop
    'Close the text reader
    inFile.Close
    MsgBox "Done."
    'Read Excel file
    Dim objFSO, objExl, objFolder, objWorkbook, strOldFile, strNewFile, intRow
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objExl = CreateObject("Excel.Application")
    'Select the folder
    Set objFolder = objFSO.GetFolder("C:\Scripts\MusicFiles")
    'Open the Excel file
    Set objWorkbook = objExl.Workbooks.Open("C:\Scripts\MusicFiles.xls")
    'Start at row 1
    intRow = 1
    'Read each Row until the end
    Do Until objExl.Cells(intRow,1).Value = ""
    'Old file name is in column 4
    strOldFile = objExl.Cells(intRow, 4).Value
    'New file name is in column 1
    strNewFile = objExl.Cells(intRow, 1).Value
    'Loop through each file in the selected folder
    For Each File In objFolder.Files
    'If the file name matches the old file name above
    If File.Name = strOldFile & ".dat" Then
    'Replace it
    File.Name = strNewFile & ".mpeg"
    End If
    Next
    'Increment each row
    intRow = intRow + 1
    Loop
    'Close Excel
    objExl.Quit
    MsgBox "Done."
    v/r LikeToCode....Mark the best replies as answers.

  • Batch renaming files and extensions?

    Can someone tell me how I can do this? I have never used terminal or automator before, so I'm not sure how to go about it.
    Thanks for any help.

    There are utilities out there that do batch renaming. Try searching VersionTracker.com and MacUpdate.com
    Next is a question of what you want to rename, and what you want to rename it to. That affects the code.
    If you are going the Unix shell scripting route, you have to be careful about spaces in names, as Unix commands are parse on white space boundaries, and so a file name with a space in it may look like 2 files, neither of which exsits. So quotes are needed to prevent that.
    Automator and Applescript are uses to spaces in filenames, you just have to master their usage. There are actual forums for Applescript
    <http://discussions.apple.com/forum.jspa?forumID=724>
    and Automator
    <http://discussions.apple.com/forum.jspa?forumID=1261>,
    which might be more helpful.

  • Automator: Impossible to rename file using automator under Mac OS X Lion

    Hi,
    Before upgrade my iMac to MAC OS X Lion 10.7.2, I had service created with automator under snow leopard in order to rename my pictures file names by blocks instead of one by one. Since I'm using Lion, this one doesn't work anymore. I have completely recreate the service under Lion and the results is the same.
    You can find below my workflow that is easy. The problem is the message error in the history of automator application. The message is "impossible to rename file "file name" because this one should create conflict with existing file". I already test a lot of times with different name where I'm sure that this one doesn't exist on my Mac but all the time without success (verify also with search function under mac)
    If somebody can help me, it would be very interesting because I already tried to find answer on internet without success too.
    Thanks in advance for your help.

    the whole automator and in particular the record action was substantially rewritten in snow leopard. and the record action is slow, unreliable and you can't trouble-shoot it. it's a wonder it works at all. the only advice i can give is to use it as little as possible. if at all possible avoid it altogether. if you do need to use it try using keyboard strokes instead of the mouse movement. for example. use command+c and command+v for copying and pasting and use tabbing to choose the correct box on the page.

  • Get old item name for renamed files using TFS API

    My current tfs will be retired in next few months.I am using tfs api to create a parallel tfs on a new server from the existing one. I have folders and solutions that have been renamed. I am iterating items and based on their changetype(add, edit, delete,
    sourcerename etc), I am checking them in destination tfs.
    I am not able to get Old filename for a file, in order to use PendRename when the item that is being iterated is Delete|SourceRename or Rename.
    I tried the mentioned solution :
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/f9c7e7b4-b05f-4d3e-b8ea-cfbd316ef737/how-to-get-previous-path-of-renamedmoved-of-file-using-tfs-api?forum=tfsgeneral
    But, my changeset has a lot of changes and hence identifying a particular file seems difficult.
    Do we have something that interraltes two items (the deleted and renamed) ones other than the changeset, because there needs to be a uniquely identifier that associated the two items so that they may appear together in TFS history?

    Hi Fabcoder,
    As Daniel mentioned, you can migrate source control files and work items to the new TFS server by using TFS integration tools.
    If the new server has the complete history, then you can view the history of the specific file to check the pervious path. Or you can do a compare between the project in new TFS where the file located with the matched project in current TFS to check
    the differences.
    Best regards, 
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Batch rename files that have non consecutive numbers?

    I have a folder with about 100 image files that have non consecutive numbers. Is there a way to rename them all to add something after the numbers (and before file type extension) without changing the numbers?
    Example: If I select 111019.003.dng and 111019.007.dng, is there a way to batch rename to 111019.003_tk.dng and 111019.007_tk.dng?
    Of course, simply batch renaming w/ a sequence number would change them to 111019.003_tk.dng and 111019.004_tk.dng. Which is no good.
    I realize the easiest way around this is to name them correctly the first time, but I am not the photographer.
    Hope this makes sense, and thanks.

    You can bulk rename in Bridge IE:-

  • Rename files using Enter key

    Using the Enter key to rename files and folders works only with items in the desktop. Everywhere else I need to use Command+Enter. Any one experiencing this behavior? Any ideas on how to make it work as it should (only Enter needed)?

    Thanks Bazsl,
    Lua is the language chosen by Adobe for plugins. It's also the language used for some of Lightroom proper.
    PS - In my opinion, Lua is a great little language, although the plugin environment is limited..

Maybe you are looking for

  • Linkage of service order with stock transfer order

    We are creating a service order for freight rate against a vendor xxx. While creating STO we assign vendor as CR (role) forwarding agent. Can we link that pricing condition of freight should pick rate directly from the ervice

  • Error While Viewing in BI answers

    Hi friends, i have three fact tables *) Actual *) Budget *) Forecast and Three dimension table *) time *) control *) project when i tried to view the answers in BI analytics page i choosed one column from the Actual fact table and Budget fact table a

  • PersonalJava 1.1 beta 1: Class not found error

    Hi there. I have a problem to run a simple java app on a pocket pc. It works if I make a executable jar file with only one class and no package structure. But if I have the class in a package the vm throws an java error: Cannot find class "de.KeyTest

  • Content based on Tabs

    I have a channel which needs to show different content based on the role and the tab the user is on . The role part is not a problem if I define that channel at the role level in Display profile xml outside the containers. But when I define this chan

  • How to stop the logonServlet

    When I run a web dynpo application and go directly to the application url (http://myserver:50000/webdynpro/dispatcher/local/TutWD_OnlineInteractiveForm/OnlineInteractiveFormApp) the view is rendered without forcing authentication, but if I go to the