首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >递归更改sed grep和sed

递归更改sed grep和sed
EN

Stack Overflow用户
提问于 2013-07-05 09:02:18
回答 1查看 271关注 0票数 0

我仍然在写这个小脚本,但是仍然有问题。获取错误

代码语言:javascript
复制
sed: no input files

我认为问题出在:

代码语言:javascript
复制
for i in `cat sed_output.txt` do sed 's/$oldstr/$newstr/g' > sed_output_new_old_string.txt done

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-05 09:11:23

如果

了解需要对其执行substitution

  • You操作的文件了解需要替换的内容了解substituted

  • You

然后;

代码语言:javascript
复制
sed 's/substitution/replacement/g' filename

将逐行扫描文件以查找替换文本,并将其替换为替换文本。

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

代码语言:javascript
复制
for file in path/to/folder; do
    sed -i.bak 's/substitute/replacement/g' "$file"
done

-i选项适用于文件更改。我给它添加了.bak,这样你就有了原始文件的备份,它将被重命名为file.bak

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17479778

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档