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

标签 linux bash ubuntu

我正在编写一个 bash 脚本,它将当前目录中文件名中的空格更改为下划线。这是脚本:

#!/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
问题是我得到这样的东西:
mv: cannot move '/home/gustavolozada/Downloads/prueba' to a subdirectory of itself, 'prueba/prueba'
我只用目录得到这个。我添加了 echo "$fil" "$name"获得更多信息,这就是它所显示的:
/home/gustavolozada/Downloads/prueba prueba
我不明白是什么问题,因为命令基本上是:
mv /home/gustavolozada/Downloads/prueba prueba
对我来说没有任何问题(除了它们是同一个文件,但我已经检查了目录中是否存在具有该名称的文件 if [[ ! -f "$name" ]]; then

最佳答案

只是一个奇怪的解释:自从name在您的错误情况下,值为 prueba/prueba , 但已通过 basename 计算,它不应包含任何斜杠。难道是Downloads/prueba是符号链接(symbolic link)吗?

关于linux - 用于从文件名中删除空格的 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64311066/

相关文章:

mysql - 将从站状态\G 显示到输出文件 '/tmp/slavestatus.txt' 中;

linux - E : Sub-process/usr/bin/dpkg returned an error code (1) whenever using apt-get

python - 如何在 Linux 上使用 Python 可逆地存储密码?

linux - 使用 ffmpeg 叠加黑线或为两个并排视频添加边框

c++ - ubuntu 服务器管道停止进程在第一次退出时终止

ubuntu - Ansible 操作未定义错误

bash - 在 ssh 之后从 lsof 杀死一个进程

java - IntelliJ 嵌入式 Java JVM 插件 bash 错误

linux - scp:如何使用过滤器从远程服务器复制文件

linux - 配置日期命令以满足我的格式