简体   繁体   English

用于从文件名中删除空格的 Bash 脚本

[英]Bash script for removing spaces from a file name

I'm writing a bash script which change spaces to underscores in the names of the files in the current directory.我正在编写一个 bash 脚本,它将当前目录中文件名称中的空格更改为下划线。 This is the script:这是脚本:

#!/bin/bash


for fil in "$(pwd)"/*; do 
    basefil=$(basename "$fil") #get name of file
    name=${basefil// /_}
    
    if [[ ! -f "$name" ]]; then
        echo "$fil" "$name"
        mv "$fil" "$name"
        
    fi
done

The problem is that I get something like this:问题是我得到了这样的东西:

mv: cannot move '/home/gustavolozada/Downloads/prueba' to a subdirectory of itself, 'prueba/prueba'

I only get this with directories.我只通过目录得到这个。 I added the echo "$fil" "$name" to get a little more info and this is what it shows:我添加了echo "$fil" "$name"以获取更多信息,这就是它显示的内容:

/home/gustavolozada/Downloads/prueba prueba

I do not understand what is the problem, because the command is basically:我不明白是什么问题,因为命令基本上是:

mv /home/gustavolozada/Downloads/prueba prueba

which to me does not have any problem whatsoever (besides the fact that they are the same file, but I already check if there is a file with that name in the directory with if [[ ! -f "$name" ]]; then这对我来说没有任何问题(除了它们是同一个文件的事实,但我已经检查目录中是否有一个具有该名称的文件if [[ ! -f "$name" ]]; then

Just a bizarre idea for an explanation: Since name in your error case has the value of prueba/prueba , but has been calculated via basename , it should not contain any slashes.只是一个奇怪的解释想法:由于您的错误案例中的name具有prueba/prueba的值,但已通过basename计算,因此它不应包含任何斜杠。 Could it be that Downloads/prueba is a symlink?难道Downloads/prueba是一个符号链接?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM