2013-07-05 72 views
0

我仍然在使用这个小脚本,但仍然有问题。收到错误递归变化sed grep和sed

sed: no input files 

我认为这个问题是:

for i in `cat sed_output.txt` do sed 's/$oldstr/$newstr/g' > sed_output_new_old_string.txt done 

echo "Enter string to be replaced" 
read OLDSTRING 
echo "Enter string to be placed" 
read NEWSTRING 
oldstr=$OLDSTRING #string to be replaced 
newstr=$NEWSTRING #new string to be placed 
echo "Enter folder path where we will find the string" 
read FOLDERPATH 

### grep oldstring and output it in grep_output.txt 
grep -rl $oldstr $FOLDERPATH > grep_output.txt 

### spaces or special characters on filenames, use sed to enclose them with quote 
for i in `cat grep_output.txt` 
do sed -e "s/'/'\\\\''/g;s/\(.*\)/'\1'/" grep_output.txt > sed_output.txt 
done 

for i in `cat sed_output.txt` 
do sed 's/$oldstr/$newstr/g' > sed_output_new_old_string.txt 
done 

回答

1

如果

  • 你知道你需要做的替换文件
  • 你知道需要取代
  • 你知道更换

又是什么;

sed 's/substitution/replacement/g' filename 

将逐行扫描文件寻找替代文本,并用替换文本替换它。

对于递归替换,你可以这样做;

for file in path/to/folder; do 
    sed -i.bak 's/substitute/replacement/g' "$file" 
done 

-i选项将做文件更改。我添加了.bak,所以你有原始文件的备份将被重命名为file.bak

如果您在sed中使用变量,那么我建议您使用"而不是',这样您的变量就可以正确插值了。

+0

我在'猫grep_output.txt' 做的sed -i “S/$ oldstr/$中newstr/G” $ I> sed_output_new_old_string.txt 做 – jmazaredo

+1

你不需要做'cat'做的,因为我。默认情况下'sed'会一行一行地解析文件。你可以简单地执行'sed's/$ oldstr/$ newstr/g“grep_output.txt>新文件'。如果您将输出重定向到新文件,则不需要'-i'选项。它仅适用于文件更改。 –