shell脚本:如何替换文件名

时间:2013-06-29 09:08:48

标签: shell replace

我想用类似于此的完整路径更改一些文件名:

/home/guest/test/home/guest/.test.log

我尝试了下面的命令,但无法搜索“/”

string="/home/guest/test"
substring="/"
replacement="/."

echo ${string/%substring/replacement}.log

2 个答案:

答案 0 :(得分:0)

在mac上使用bash创建,因此它可能适用于您使用的任何shell ...

string="/home/guest/test"
echo $string | sed  's/\/\([^\/]\{0,\}\)$/\/.\1.log/'

使用简单的shell字符串替换不起作用,因为我知道你无法将最后一次出现的/符号作为唯一的替换。

<强>更新 实际上,如果你知道它总是“/ two / directories / in”

,我会想到另一种方法
string="/home/guest/test"
firstpartofstring=$(echo $string |  cut -d\/ -f1-3)
lastpartofstring=$(echo $string |  cut -d\/ -f4)
echo ${firstpartofstring}/.${lastpartofstring}.log

答案 1 :(得分:0)

您可以执行以下操作:

for file in /home/guest/*; do 
    name=${file##*/}
    path=${file%/*}
    mv "$file" "$path"'/.'"$name"'.log'
done
相关问题