我正在运行一个名为 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/