Find and replace filename recursively in a directory

前端 未结 14 1779
野趣味
野趣味 2020-11-28 21:24

I want to rename all the files in a folder which starts with 123_xxx.txt to xxx.txt.

For example, my directory has:

123_xxx         


        
相关标签:
14条回答
  • 2020-11-28 22:11

    Tried the answer above but it didn't work for me cause i had the string inside folders and files name at the same time so here is what i did the following bash script:

      for fileType in d f
      do
        find  -type $fileType -iname "stringToSearch*" |while read file
        do
          mv $file $( sed -r "s/stringToSearch/stringToReplaceWith/" <<< $file )
        done
      done
    

    First i began by replacing inside folders name then inside files name.

    0 讨论(0)
  • 2020-11-28 22:15

    To expand on Sorpigal's answer, if you want to replace the 123_ with hello_, you could use

        find . -name '123*.txt' -type f -exec bash -c 'mv "$1" "${1/\/123_/\/hello_}"' -- {} \;
    
    0 讨论(0)
  • 2020-11-28 22:16

    A slight variation on Kent's that doesn't require gawk and is a little bit more readable, (although, thats debatable..)

    find . -name "123*" | awk '{a=$1; gsub(/123_/,""); printf "mv \"%s\" \"%s\"\n", a, $1}' | sh

    0 讨论(0)
  • 2020-11-28 22:18

    If the names are fixed you can visit each directory and perform the renaming in a subshell (to avoid changing the current directory) fairly simply. This is how I renamed a bunch of new_paths.json files each to paths.json:

    for file in $(find root_directory -name new_paths.json)
      do
         (cd $(dirname $file) ; mv new_paths.json paths.json)
      done
    
    0 讨论(0)
  • 2020-11-28 22:21

    you could check 'rename' tool

    for example

    rename 's/^123_//' *.txt
    

    or (gawk is needed)

    find . -name '123_*.txt'|awk '{print "mv "$0" "gensub(/\/123_(.*\.txt)$/,"/\\1","g");}'|sh
    

    test:

    kent$  tree
    .
    |-- 123_a.txt
    |-- 123_b.txt
    |-- 123_c.txt
    |-- 123_d.txt
    |-- 123_e.txt
    `-- u
        |-- 123_a.txt
        |-- 123_b.txt
        |-- 123_c.txt
        |-- 123_d.txt
        `-- 123_e.txt
    
    1 directory, 10 files
    
    kent$  find . -name '123_*.txt'|awk '{print "mv "$0" "gensub(/\/123_(.*\.txt)$/,"/\\1","g");}'|sh
    
    kent$  tree
    .
    |-- a.txt
    |-- b.txt
    |-- c.txt
    |-- d.txt
    |-- e.txt
    `-- u
        |-- a.txt
        |-- b.txt
        |-- c.txt
        |-- d.txt
        `-- e.txt
    
    1 directory, 10 files
    
    0 讨论(0)
  • 2020-11-28 22:23

    Provided you don't have newlines in your filenames:

    find -name '123_*.txt' | while IFS= read -r file; do mv "$file" "${file#123_}"; done
    

    For a really safe way, provided your find supports the -print0 flag (GNU find does):

    find -name '123_*.txt' -print0 | while IFS= read -r -d '' file; do mv "$file" "${file#123_}"; done
    
    0 讨论(0)
提交回复
热议问题