Home > command line > How to change extension of multiple files from command line?

How to change extension of multiple files from command line?

April 19Hits:1
Advertisement

I have many files with .abc extension and want to change them to .edefg
How to do this from command line ?

EDIT: I have a root folder with many sub-folders, so the solution should work -r recursively.

Answers

A portable way (which will work on any POSIX compliant system):

find /the/path -depth -name "*.abc" -exec sh -c 'mv "$1" "${1%.abc}.edefg"' _ {} \;

In bash4, you can use globstar to get recursive globs (**):

shopt -s globstar
for file in /the/path/**/*.abc; do
  mv "$file" "${file%.abc}.edefg"
done

The (perl) rename command in ubuntu can rename files using perl regular expression syntax, which you can combine with globstar or the find command:

# Using globstar
shopt -s globstar
files=(/the/path/**/*.abc)  

# Best to process the files in chunks to avoid exceeding the maximum argument
# length. 100 at a time is probably good enough.
# See http://mywiki.wooledge.org/BashFAQ/095
for ((i = 0; i < ${#files[@]}; i += 100)); do
  rename 's/\.abc$/.edefg/' "${files[@]:i:100}"
done

# Using find:
find /the/path -depth -name "*.abc" -exec rename 's/\.abc$/.edefg/' {} +

Also see http://mywiki.wooledge.org/BashFAQ/030

This will do the required task if all the files are in the same folder

rename 's/.abc$/.edefg/' *.abc

To rename the files recursively use this:

find /path/to/root/folder -type f -name '*.abc' -print0 | xargs -0 rename 's/.abc$/.edefg/'

One problem with recursive renames is that whatever method you use to locate the files, it passes the whole path to rename, not just the file name. That makes it hard to do complex renames in nested folders.

I use find's -execdir action to solve this problem. If you use -execdir instead of -exec, the specified command is run from the subdirectory containing the matched file. So, instead of passing the whole path to rename, it only passes ./filename. That makes it much easier to write the regex.

find /the/path -type f \
               -name '*.abc' \
               -execdir rename 's/\.\/(.+)\.abc$/version1_$1.abc/' {} \;

In detail:

  • -type f means only look for files, not directories
  • -name '*.abc' means means only match filenames that end in .abc
  • The backslashes after -type and -name are the bash line-continuation character. I use them to make this example more readable, but they are not needed in practice.
  • However, the backslash at the end of the -execdir line is required. It is there to esacpe the semicolon, which terminates the command run by -execdir. Fun!

Explanation of the regex:

  • s/ start of the regex
  • \.\/ match the leading ./ that -execdir passes in. Use \ to escape the . and / metacharacters
  • (.+) match the filename. The parentheses capture the match for later use
  • \.abc escape the dot, match the abc
  • $ anchor the match at the end of the string
  • / marks the end of the "match" part of the regex, and the start of the "replace" part
  • version1_ add this text to every file name
  • $1 references the existing filename, because we captured it with parentheses. If you use multiple sets of parentheses in the "match" part, you can refer to them here using $2, $3, etc.
  • .abc the new file name will end in .abc. No need to escape the dot metacharacter here in the "replace" section
  • / end of the regex

Before

tree --charset=ascii

|-- a_file.abc
|-- Another.abc
|-- Not_this.def
`-- dir1
    `-- nested_file.abc

After

tree --charset=ascii

|-- version1_a_file.abc
|-- version1_Another.abc
|-- Not_this.def
`-- dir1
    `-- version1_nested_file.abc



Hint: rename's -n option is useful. It does a dry run and shows you what names it will change, but does not make any changes.

Another portable way:

find /the/path -depth -type f -name "*.abc" -exec sh -c 'mv "$1" "$(dirname "$1")/$(basename "$1" .abc).edefg"' _ {} \;

Related Articles

  • How to change extension of multiple files from command line?April 19

    I have many files with .abc extension and want to change them to .edefg How to do this from command line ? EDIT: I have a root folder with many sub-folders, so the solution should work -r recursively. --------------Solutions------------- A portable w

  • "wput" multiple files from command line?May 2

    You can upload a single file with wput: wput file ftp://username:[email protected]/file is there a way to upload multiple? Maybe something like: wput {file1,file2} ftp://username:[email protected]/{file1,file2} Note: I know there are solutions using ft

  • Ubuntu - Execute multiple php files via command lineApril 29

    How do I execute multiple php files via command line? --------------Solutions------------- Just call them one after each other: a.php; b.php; c.php Or if you don't want to type out all the names: ls *.php | xargs -tn1 php This being Unix, there are m

  • Running class and bst file through command line/shell scriptJune 6

    I am trying to run the latex project: http://www.sigchi.org/publications/chipubform/sigchi-papers-latex-template/at_download/file through command line. I have written a shell script(*.sh file), where I plan to execute *.tex with pdflatex, and *.bib w

  • Editing a file from command line adds strange chars to the file

    Editing a file from command line adds strange chars to the fileAugust 5

    I just edited a vhost file via command line sudo vi /srv/.../vhost.conf After saving and reopening to add something, strange chars where added to the file: E.g. AuthName "trac"n was AuthName "trac" before. Same with AuthUserFile. A ns

  • On Mac, how to open a file from command line and have it shown in an existing Emacs window?April 24

    How to open a file from command line and have it shown in one of the existing windows in the existing frame, otherwise in a new window in a new frame? The default behavior is it is opened in a new frame. I'm using GNU Emacs 23.4.1 (x86_64-apple-darwi

  • Copying files from command line to clipboardNovember 1

    In a GUI file manager it is possible to select a few files, press Ctrl-C (which supposedly copies come info about the files to clipboard), then navigate to another folder and press Ctrl-V, which will then copy the files into that directory. As an exp

  • How can I view a .eml file from command line in Windows Vista?December 19

    Ok, so my parent's computer crashed (horribly - corruptedRegistry) and I'm trying to access one of their e-mail files that is saved locally on the hard drive. I can't launch Windows itself so right now I am in a "bootup command prompt". I've nav

  • Generating a MSS file at command-line?February 12

    Is there a way to generate a mss file from the exported SDK XML file at command-line? At the moment, I still have to open xsdk, generate a new hello world project to create the mss file. But I would like to generate the mss file with makefiles. -----

  • Print text file from command line without shell "print" commandFebruary 12

    I have a printer, an HP DeskJet 712C, that I cannot print to via the shell "print" command in Windows 7 or Windows XP. I think this is because this particular printer is a "software" printer, something like a "software" modem

  • Create self-extracting EXE from ZIP file in command line

    Create self-extracting EXE from ZIP file in command lineApril 4

    I have installed WinZip 9.0 SR1 in my system and I want to create a executable from a zip file in command line. I have tried with the following command line statement C:\Users\admin\Desktop>"C:\Program Files (x86)\WinZip 9.0 SR1\WZSEPE32.EXE"

  • Print documents to PDF files via command line in WineDecember 24

    I have a task to use Wine on Linux distributive for work with MS Office files doc[x] / xls[x] / ppt[x] and pdf via virtual printer. Output formats I need are png or jpg. This is for converter of documents and presentations. I can convert a ps file wh

  • How to get a list of applications associated with a file using command lineFebruary 7

    File associations usually are made in the desktop environment, but how to get a list of applications associated with a file using command line? Something like: $ getassoc foo.pdf <CR> $ acroread, okular Does not need to be a command, can a cat + gre

  • Linux browse and open network files with command lineJune 1

    I'm new to Linux. I have a Windows network connected to a Linux computer. When I try to browse Windows files from windows managers in Linux, it asks for user name, work group name and password. The address of computer network is something like this:

  • What is the difference between copy and paste a file using command line terminal and GUI copy paste?August 8

    What is the difference between copy and paste a file using command line terminal and GUI copy paste ? Which one is fast ? I think both are same because of same program will execute in background . What am i asking is, in windows or linux ...i want to

  • Print markdown file from command lineSeptember 5

    I was looking for a way to print a markdown file from command line. I usually use lp for simple text files; I want to use something like that, but for markdown. Also it would be great that this printing could take care of hyphenation (my actual appro

  • How to set languages/shortcuts from config files or command line?April 2

    I need to provision several Ubuntu 14.04/14.10 desktops. Most things I've been able to provision easily because they can be set in config files or from the command line. But I'm having trouble with 2 things, setting the available languages and settin

  • Possible to compile a tex file with command line arguments passed to the tex file?May 8

    Is it possible to compile a tex file with command line arguments passed to the tex file? For example, a tex file merge.tex \documentclass{article} \usepackage{pdfpages} \begin{document} \includepdf[pages=-,fitpaper]{1.pdf} \includepdf[pages=-,fitpape

  • How to remove all comments/annotations in multiple pdfs from command lineAugust 9

    Are there any open source solution to remove all the comments/annotations from PDF files using command line? I searched around, and it seems that there are solutions with commercial software, e.g. , by javascripting Acrobat Pro. The non-free cpdf als

  • Load a Scala File From Command LineJanuary 28

    I'm fairly new to Scala and I'm having troubles running a .scala file from command line. I've tried the following commands 1.\PathToDirContaingingCode> scala myCode.scala 2.\PathToDirContaingingCode> scala scala> :load myCode.scala 3.\PathToDirCo

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.956 s.