Yong
Yong

Reputation: 33

How to quickly rename my files on macOS or linux from CLI?

Here're my source files.

e2f9eb91-645f-408a-9241-66490b61a617_file-module-1.txt
d20f06a8-4de1-4da0-8175-93e9b2d81c42_file-module-2.txt
6740a19f-e1a0-43da-9a01-9e873238360e_file-module-3.txt
.
.
.

I need to figure it out a way to rename all the files to remove the first 36 characters up to _file or replacing as something else. I am expecting all the files are as below.

_file-module-1.txt or Yong_file-module-1.txt
_file-module-2.txt or Yong_file-module-2.txt
_file-module-3.txt or Yong_file-module-3.txt
.
.
.

Thanks in advance!

Upvotes: 2

Views: 603

Answers (4)

kmdpl
kmdpl

Reputation: 46

Easiest way to do this would be to use a combination of find, sed and xargs.

find . -name '*.txt' | sed 'p;s/.*_file/Yong_file/' | xargs -n2 mv

This finds text files in the current working directory, echoes the original file name (p) and then a modified name (s/.*_file/Yong_file/) and feeds it all to mv in pairs (xargs -n2).

Upvotes: 1

user1934428
user1934428

Reputation: 22225

If you would use zsh, you could do a

 autoload zmv # Because zmv is not active by default
 zmv '????????????????????????????????????(*module*txt)' '_$1'

Since you want to use bash, you could steal it from zsh and use it within bash like this:

zsh -c "autoload zmv; zmv '????????????????????????????????????(*module*txt)' '_$1'"

(These should be 36 question marks; better you count them again instead of blindly copying this code).

Upvotes: 0

Mark Setchell
Mark Setchell

Reputation: 207385

You can use rename like this:

rename --dry-run 's/.*_file/Yong_file/' *.txt

If you are on macOS, you can install rename with homebrew:

brew install rename

Upvotes: 2

Cyan
Cyan

Reputation: 329

If you use mac, you can simply try this via UI: https://support.apple.com/en-us/guide/mac-help/mchlp1144/mac

Or if you want to try those work via CLI: https://www.howtogeek.com/423214/how-to-use-the-rename-command-on-linux/ (read from Renaming Multiple Files with mv)

This might help also; sed commands of linux: https://www.geeksforgeeks.org/sed-command-in-linux-unix-with-examples/

and another stackoverflow article: bash substitute first character in every line

Upvotes: 1

Related Questions