Linux Shell-更改文件名而不更改给定路径的扩展名

Linux Shell-更改文件名而不更改给定路径的扩展名,linux,bash,shell,Linux,Bash,Shell,我正在编写一个脚本,在该脚本中,我在不更改给定路径的扩展名的情况下,遍历文件夹并重命名文件。我使用find获取文件的路径,例如 abc/xyz/qwe.txt 现在,我接受用户提供的文件名,并希望将该文件重命名为 abc/xyz/myfile.txt 有什么办法可以解决这个问题。如何重命名该文件?我试过下面的代码 find "$input_variable" -type f -name $word.* | while read file; do mv $file | sed "s/$word/

我正在编写一个脚本,在该脚本中,我在不更改给定路径的扩展名的情况下,遍历文件夹并重命名文件。我使用find获取文件的路径,例如

abc/xyz/qwe.txt

现在,我接受用户提供的文件名,并希望将该文件重命名为

abc/xyz/myfile.txt

有什么办法可以解决这个问题。如何重命名该文件?我试过下面的代码

find "$input_variable" -type f -name $word.* | while read file; do  mv $file | sed "s/$word/$replace/"; done;;
更新 试试这个

echo "Please Insert the path of the folder"
read input_variable

read -p "Enter the word to find = " word
read -p "Enter word to replace = " replace

find "$input_variable" -type f -name "$word.*" | while read file; 
do
    echo "$file"
    s="$file"
    d="`dirname $s`"
    f="`basename $s`"
    nf=$(echo $f | sed "s/^[^.]*\./$word./")
    newFileName="$d/$nf"
done
这可能是一种方式:

find "$input_variable" -type f -name "$word.*" | while read file; do
    dir=${file%/*}
    base=${file##*/}
    ext=${base##*.}
    noext=${base:0:${#base} - ${#ext} - 1}
    newname=${noext/"$word"/"$replace"}.$ext
    echo mv "$file" "$dir/$newname"
done
当您确定回音部分已经正确时,请将其删除

编辑:


再次更新它,因为OP似乎使用了一些旧shell:

$ echo "$newFileName"
abc/xyz/myfile.txt
使用和:

测试:

$ echo "$newFileName"
abc/xyz/myfile.txt

围绕你的回声塞德。。在
$(…)
中,在
的开头添加一个
do
,而
-loop@umläute my bad is a typo更新了问题35; konsolebox谢谢您的回复。使用您的代码会出现错误替换。@ArihantGodha我猜您没有使用bash。您正在使用什么shell?在noext=${base:0:${{base}-${{ext}-1}PID TTY TIME CMD 3876 pts/0 00:00:00 bash中,它终于工作了。:)使用bash filename.sh运行。干杯,我可以传递一个变量来代替myfile吗。我已经尝试了nf=$(sed的/^[^.]*\./“$word”。/”感谢您的回复,但这里出现了意外的重定向nf=$(sed的/^[^.]*\./$word./'进行了另一次编辑以删除
似乎您正在使用一些旧的shell。再次编辑它,现在再试。同时告诉您在执行
echo$shell
时看到的内容。您可以将所有这些命令放在一个文件中,并像
bash c“script.sh”
echo$shell输出=/bin/bash我的bash版本是GNU bash,版本4.2.45(1)-发布(i686 pc linux gnu)
$ echo "$newFileName"
abc/xyz/myfile.txt