根据文本文件名创建目录名称

时间:2014-10-09 02:48:35

标签: 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')

AND

//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'\'')\""' - {} \;)

1 个答案:

答案 0 :(得分:1)

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