0

我正在编写一个 shell 脚本,它在文件中找到给定的文本并从指定的路径替换它,并在替换文本后,用给定的单词重命名该文件。使用 sed 时出现权限被拒绝的错误。我的脚本看起来像这样

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

    read -p "You entered: $input_variable is correct y/n  " yn

    read -p "Enter the word to find = " word
    read -p "Enter word to replace = " replace
    case $yn in
        [Yy]* ) find "${input_variable}" -type f -iname "${word}.*" | while read filename; do "`echo "${filename}" | sed -i 's/$word/$replace/g' ${filename}| sed -i 's/\$word/\$replace/' ${filename}`"; done ;;
        [Nn]* ) exit;;
        * ) echo "Please answer yes or no.";;
    esac`

我收到以下错误

bulk_rename.sh: 34: bulk_rename.sh: : 权限被拒绝

有什么建议么 ?

在@vijay 的建议更新了脚本之后

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

read -p "You entered: $input_variable is correct y/n  " yn

read -p "Enter the word to find = " word
read -p "Enter word to replace = " replace
case $yn in
    [Yy]* ) find "${input_variable}" -type f -iname "${word}.*" | while read filename; do 
    perl -pi -e 's/$word/$replace' ${filename}
    mv ${filename} $word;   done;;

    [Nn]* ) exit;;
    * ) echo "Please answer yes or no.";;
esac

现在我得到以下


替换替换未在 -e 第 1 行终止

这是我 chmod 并显示输出时得到的

abc@PC-DEV-41717:~/Documents/blog$ chmod +x bulk_rename.sh ; /bin/ls -l bulk_rename.sh
chmod +x bulk_rename.sh ; /bin/ls -l bulk_rename.sh
+ chmod +x bulk_rename.sh
+ /bin/ls -l bulk_rename.sh
-rwxrwxr-x 1 abc abc 1273 Aug  1 16:51 bulk_rename.sh
4

3 回答 3

1

最后,我使用 SED 解决了我的问题,并借助我提出的这个问题

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

read -p "You entered: $input_variable is correct y/n  " yn

read -p "Enter the word to find = " word
read -p "Enter word to replace = " replace
case $yn in
    [Yy]* ) grep -r -l "$word" $input_variable  | while read file; do echo $file; echo $fname; sed -i "s/\<$word\>/$replace/g" $file ; done; find "$input_variable" -type f -name "$word.*" | while read file; do dir=${file%/*};  base=${file##*/}; noext=${base%.*}; ext=${base:${#noext}}; newname=${noext/"$word"/"$replace"}$ext; echo mv "$file" "$dir/$newname"; done;;
    [Nn]* ) exit;;
    * ) echo "Please answer yes or no.";;
esac
于 2013-08-07T10:58:52.343 回答
0

我猜你让它变得复杂了:为什么不用两个简单的语句让它变得简单。由您决定如何将以下语句用于您的目的:

perl -pi -e 's/wordtofind/wordtoreplace' your_file #for replacing the word in the file

mv your_file wordtoreplace  #for renaming the file
于 2013-08-01T09:06:33.490 回答
0

改变

   perl -pi -e 's/$word/$replace' ${filename}

   perl -pi -e "s/$word/$replace/" ${filename}
 --------------^----------------^^--------

错误消息表明缺少 `/' 字符。


另外,那么您知道原始代码会出现什么错误?

请注意,您需要在 sed 周围加上 dbl 引号,就像在 perl 中一样,因此 shell 可以替换这些值。IE

..... | sed -i "s/$word/$replace/g"
     ----------^------------------^

这假设没有顽皮的字符,尤其是/$wordor内部$replace

IHTH

于 2013-08-02T14:36:50.283 回答