2013-08-01 76 views
0

我正在编写一个shell脚本,它在文件中查找给定的文本并将其替换为指定的路径,并在替换文本之后,将该文件重命名为与给定的词。 我在使用sed时遇到拒绝权限错误。我的脚本看起来像这样使用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并显示输出

[email protected]:~/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 
+0

'使用chmod + X bulk_rename.sh' – devnull

+0

也许你没有权限编辑有问题的文件。 – devnull

+0

感谢您的快速回复@devnull我已经尝试更改权限,它给了我同样的问题。 –

回答

1

最后我带着我使用SED和我的问题的解决这个问题的帮助,我也问过Question

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 
0

我想你会变得很复杂: 为什么不用两个简单的句子来简化它。它取决于你如何使用下面的语句为你的目的:

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

mv your_file wordtoreplace #for renaming the file 
+0

谢谢@Vijay ..我是新的shell脚本。我将拥有一个我将要编辑的文件列表。所以你推荐的是我的上面的脚本是正确的,因为我提示用户的一切。和sed有何不同。 –

0

变化

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

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

的错误味精表示缺少'/”字符。


另外,你知道什么错误得到你的原代码?

请注意,您将需要dbl引号围绕您的sed,就像在perl中一样,所以shell可以替换值。即

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

这假定有不调皮字符,尤其是/内部的$word$replace

IHTH

相关问题