Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively prepend text to file names

Tags:

linux

bash

rename

I want to prepend text to the name of every file of a certain type - in this case .txt files - located in the current directory or a sub-directory.

I have tried:

find -L . -type f -name "*.txt" -exec mv "{}" "PrependedTextHere{}" \;

The problem with this is dealing with the ./ part of the path that comes with the {} reference.

Any help or alternative approaches appreciated.


1 Answers

You can do something like this

find -L . -type f -name "*.txt" -exec bash -c 'echo "$0" "${0%/*}/PrependedTextHere${0##*/}"' {} \;

Where

  • bash -c '...' executes the command
  • $0 is the first argument passed in, in this case {} -- the full filename
  • ${0%/*} removes everything including and after the last / in the filename
  • ${0##*/} removes everything before and including the last / in the filename

Replace the echo with a mv once you're satisfied it's working.

like image 65
Reinstate Monica Please Avatar answered Dec 01 '25 08:12

Reinstate Monica Please



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!