linux - 根据文本文件名创建目录名

标签 linux bash shell unix

我正在运行一个名为 filename_to_dir.sh 的脚本,它在一个 while 循环中接受一个参数 -s。该参数是一个 .txt 文件名。我正在使用 while 循环对它在特定目录中找到的每个文件执行脚本,然后使用格式化的文件名创建子目录。但在创建任何目录之前,文件名会被格式化并去除空格和其他一些东西,以避免在将其提供给 filename_to_dir.sh 时出错。唯一的问题是目录正在用格式化的名称创建,但文本文件名保持不变。如何根据格式化的文件名创建目录?

当前结果:

|-- text_files
|   |-- this_is_new-1
|   |-- test_11-today
|   |-- hi_hi-Bye
|   |-- this is new - 1.txt
|   |-- test 11 - today.txt
|   |-- hi HI - Bye.txt

期望的结果:

|-- text_files
|   |-- this_is_new-1
|   |-- test_11-today
|   |-- hi_hi-Bye
|   |-- this_is_new-1.txt
|   |-- test_11-today.txt
|   |-- hi_hi-Bye.txt

我尝试过的两种方式:

while read -r file; do
    new_file=$(echo "$file" | sed -re 's/^([^-]*)-\s*([^\.]*)/\L\1\E-\2/' -e 's/ /_/g' -e 's/_-/-/g')
    if [ "$file" != "$new_file" ]; then
        echo mv "$file" "$new_file"
        file_split.sh -s $file
    fi
done < <(find $FILE_PATH -type f -name '*.txt')

//Using find but i loose a way to check if file has been renamed already
while read -r file; do
    file_split.sh -s $file 
done < <(find $FILE_PATH -type f -exec bash -c 'echo "mv \"$1\" \"$(echo "$1" | sed -re '\''s/^([^-]*)-\s*([^\.]*)/\L\1\E-\2/'\'' -e '\''s/ /_/g'\'' -e '\''s/_-/-/g'\'')\""' - {} \;)

最佳答案

我认为您应该将 echo mv "$file""$new_file" 更改为 mv "$file""$new_file"

关于linux - 根据文本文件名创建目录名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26269503/

相关文章:

linux - AT91(Cortex A5 ARM,无GPU)3D图形应用程序开发解决方案

java SSLHandshakeException 虽然证书受信任的系统范围

bash - 尝试在给定文件的每一行末尾添加一个字符,是如何完成的?

linux - 如何更改许多文件的符号链接(symbolic link)路径?

linux - 解压不到一天的文件

php - 使用 ssh 和 shell 从另一个 php 脚本在 Linux 服务器中运行 php 脚本

linux - 如何用包含逗号的awk编写csv文件

Linux:如何将 USB 驱动程序分配给设备

linux - 通过 Bash 脚本检索进程网络使用情况(自重启以来,如果需要)

linux - 为什么在ubuntu14.04中删除后又出现该目录