-1

I have several files in a folder. I have to match the filenames using a regex pattern. In the regex pattern I have a word which would be a variable. I want all the files matched with the pattern to be moved to a separate directory with an alternate filename replacing the string with which I had made the match.

Eg,

I have many files with filenames having the word foo in the directory like,

gadgeagfooafsa
fsafsaffooarwf
fasfsfoofsafff

I have to list these files and copy it to another directory replacing the word foo from it. I have specified the new pattern to be "kuh", Like the above files should be copied to the new folder as

gadgeagkuhafsa
fsafsafkuharwf
fasfskuhfsafff

Finally, can I pipe different commands together to execute these in one line? :)

I had tried this command, but it didn't work, somehow the copy is failing.

ls | grep ".*foo[} ].*" | xargs cp -t work/
Gopikrishnan R
  • 11
  • 1
  • 1
  • 4

3 Answers3

0

find + bash solution:

find . -type f -name "*foo*" -exec bash -c 'fn=${0##*/}; cp "$0" "new_dest/${fn//foo/kuh}"' {} \;
  • fn=${0##*/} - extracting file basename
  • ${fn//foo/kuh} - substituting foo with kuh in filename

Replace/adjust new_dest with your current destination directory name.

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

I chose /tmp as the new destination, and only used two of the example files

newdest="/tmp"; fp="foo"; np="kuh"; for f in $(find . -type f -name "*$fp*"); do new=$(echo $f| sed  "s/$fp/$np/g"); cp -f $f $newdest/$new ; done

which moves and renames the files

ls /tmp/*kuh*
/tmp/fsafsafkuharwf  /tmp/gadgeagkuhafsa
Calvin Taylor
  • 664
  • 4
  • 15
0

If all the files are in same folder

with bash

for i in *foo* ;do mv "$i" /tmp/"${i/foo/kuh}";done
ctac_
  • 2,413
  • 2
  • 7
  • 17