shell脚本:如何替换文件名
我想更改一些完整路径的文件名,如下所示:shell脚本:如何替换文件名,shell,replace,Shell,Replace,我想更改一些完整路径的文件名,如下所示: /home/guest/test ⟶ /home/guest/.test.log 我尝试了下面的命令,但它无法搜索“/” 在mac上使用bash创建,因此它可以与您正在使用的任何shell一起使用 string="/home/guest/test" echo $string | sed 's/\/\([^\/]\{0,\}\)$/\/.\1.log/' 使用简单的shell字符串替换是行不通的,因为我知道没有任何方法可以将最后出现的/符号作为唯一的替
/home/guest/test
⟶ <代码>/home/guest/.test.log
我尝试了下面的命令,但它无法搜索“/”
在mac上使用bash创建,因此它可以与您正在使用的任何shell一起使用
string="/home/guest/test"
echo $string | sed 's/\/\([^\/]\{0,\}\)$/\/.\1.log/'
使用简单的shell字符串替换是行不通的,因为我知道没有任何方法可以将最后出现的/符号作为唯一的替换
更新:
事实上,如果你知道它总是“/two/directories/in”,我会想出另一种方法
您可以执行以下操作:
for file in /home/guest/*; do
name=${file##*/}
path=${file%/*}
mv "$file" "$path"'/.'"$name"'.log'
done
find/opt-type f-exec echo{}\|sed's/\/([^\/]*)$/\/.\1.为i-in/home/guest/锁定/;dop=
dirname$i
;F=basename$i
;回声$P“/”$F“.lock”;donefind.|sed“s/(.*)\/(.*)/\1\/.\2.lock/”
string="/home/guest/test"
firstpartofstring=$(echo $string | cut -d\/ -f1-3)
lastpartofstring=$(echo $string | cut -d\/ -f4)
echo ${firstpartofstring}/.${lastpartofstring}.log
for file in /home/guest/*; do
name=${file##*/}
path=${file%/*}
mv "$file" "$path"'/.'"$name"'.log'
done