Accueil > Système > Rename all files which contain the sub-string ‘foo’, replacing it with ‘bar’

Rename all files which contain the sub-string ‘foo’, replacing it with ‘bar’

12/02/2024 Categories: Système Tags: ,
Print Friendly, PDF & Email

Source: commandlinefu.com

Terminal – Rename all files which contain the sub-string ‘foo’, replacing it with ‘bar’

for i in ./*foo*;do mv -- "$i" "${i//foo/bar}";done

Rename all files which contain the sub-string ‘foo’, replacing it with ‘bar’

That is an alternative to command 8368.

Command 8368 is EXTREMELY NOT clever.

  1. Will break also for files with spaces AND new lines in them AND for an empty expansion of the glob ‘*’
  2. For making such a simple task it uses two pipes, thus forking.
  3. xargs(1) is dangerous (broken) when processing filenames that are not NUL-terminated.
  4. ls shows you a representation of files. They are NOT file names (for simple names, they mostly happen to be equivalent). Do NOT try to parse it.

Why? see this :http://mywiki.wooledge.org/ParsingLs

Recursive version:

find . -depth -name "*foo*" -exec bash -c 'for f; do base=${f##*/}; mv -- "$f" "${f%/*}/${base//foo/bar}"; done' _ {} +

Alternatives

ls * | sed -e 'p;s/foo/bar/' | xargs -n2 mv

Renames all files in a directory named foo to bar.

  • foobar1 gets renamed to barbar1
  • barfoo2 gets renamed to barbar2
  • fooobarfoo gets renamed to barobarfoo

NOTE: Will break for files with spaces AND new lines AND for an empty expansion of the glob ‘*’


rename 's/foo/bar/g' ./* $ ls
thisFileIsCalledDAVE
$ rename 's/DAVE/PETE/g' ./*
$ ls
thisFileIsCalledPETE

Would this command line achieve the desired function? My CLI knowledge is not great so this could certainly be wrong. It is merely a suggestion for more experienced uses to critique. Best wishes roly 🙂

Lire aussi:  How to install PSAD Intrusion Detection on Ubuntu 16.04 LTS server

for f in *; do mv "$f" "${f/foo/bar}"; done

without sed, but has no problems with files with spaces or other critical characters


ls | sed 'p;s/foo/bar/' | xargs -n2 mv

rename foo bar directory/filename

rename command in my system -Fuduntu running 2.6.38 Linux Kernel- is an ELF 64-bit LSB executable, not a Perl script. man page for rename command shows syntax as « rename from to where » (or something like that), so I am doing just what I have been told…

 

Categories: Système Tags: ,
Les commentaires sont fermés.