使用Shell脚本和sed - 查找并替换文件中的单词并重命名文件

时间:2013-08-01 06:25:00

标签: shell sed shell-exec

我正在编写一个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:bulse_rename.sh :: Permission denied

有什么建议吗?

@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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我猜你让它变得复杂: 为什么不用两个简单的声明来简化它。由您决定如何将以下陈述用于您的目的:

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

mv your_file wordtoreplace  #for renaming the file

答案 2 :(得分:0)

更改

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

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

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


另外,您知道错误与原始代码有关吗?

请注意,你需要在你的sed周围使用dbl-quotes,就像在perl中一样,所以shell可以替换值。即。

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

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

IHTH