Linux - Replacing spaces in the file names

前端 未结 11 659
臣服心动
臣服心动 2021-01-29 18:21

I have a number of files in a folder, and I want to replace every space character in all file names with underscores. How can I achieve this?

相关标签:
11条回答
  • 2021-01-29 18:57

    Here is another solution:

    ls | awk '{printf("\"%s\"\n", $0)}' | sed 'p; s/\ /_/g' | xargs -n2 mv
    
    1. uses awk to add quotes around the name of the file
    2. uses sed to replace space with underscores; prints the original name with quotes(from awk); then the substituted name
    3. xargs takes 2 lines at a time and passes it to mv
    0 讨论(0)
  • 2021-01-29 19:01

    I prefer to use the command 'rename', which takes Perl-style regexes:

    rename "s/ /_/g" *
    

    You can do a dry run with the -n flag:

    rename -n "s/ /_/g" *
    
    0 讨论(0)
  • 2021-01-29 19:01

    What if you want to apply the replace task recursively? How would you do that?

    Well, I just found the answer myself. Not the most elegant solution, (also tries to rename files that do not comply with the condition) but it works. (BTW, in my case I needed to rename the files with '%20', not with an underscore)

    #!/bin/bash
    find . -type d | while read N
    do
         (
               cd "$N"
               if test "$?" = "0"
               then
                   for file in *; do mv "$file" ${file// /%20}; done
               fi
         )
    done
    
    0 讨论(0)
  • 2021-01-29 19:05

    Try something like this, assuming all of your files were .txt's:

    for files in *.txt; do mv “$files” `echo $files | tr ‘ ‘ ‘_’`; done
    
    0 讨论(0)
  • 2021-01-29 19:05

    I believe your answer is in Replace spaces in filenames with underscores.

    0 讨论(0)
提交回复
热议问题