从unix终端搜索和替换多个文件上的字符串

从unix终端搜索和替换多个文件上的字符串,unix,sed,terminal,replace,Unix,Sed,Terminal,Replace,我们正在将代码库中的所有静态html页面转换为php页面。第一步是将所有的.html文件扩展名改为.php(我已经这样做了)。第二步是更新每个html页面中的所有链接,以指向新的php页面 (例如,在index.php中,我有到contact.html和about-us.html的链接。现在,由于我们将每个.html文件扩展名替换为.php,我们需要将contact.html更改为contact.php,同样地,about-us.html更改为about-us.php) 我现在要做的是在多个文件

我们正在将代码库中的所有静态html页面转换为php页面。第一步是将所有的.html文件扩展名改为.php(我已经这样做了)。第二步是更新每个html页面中的所有链接,以指向新的php页面

(例如,在index.php中,我有到contact.html和about-us.html的链接。现在,由于我们将每个.html文件扩展名替换为.php,我们需要将contact.html更改为contact.php,同样地,about-us.html更改为about-us.php)

我现在要做的是在多个文件中搜索特定字符串。(在许多文件中搜索“contact.html”,如index.php、index2.php、index3.php等)之后,将所有这些文件中的所有“contact.html”替换为“contact.php”

我不熟悉unix命令行,到目前为止,我在论坛上看到了其他人的类似问题,但不太明白哪一个可以帮助我实现我想要的。我正在使用cygwin,如果可能的话,我需要在没有perl脚本的情况下解决这个问题,因为我没有安装它。我需要尝试使用sed、grep、find或其他任何工具

所以,如果你们中有人认为这是一个重复的,请告诉我一个相关的职位在那里。谢谢您的时间。

这应该有用(在这里找到:):

试试这个:

find-名称'*.html'-exec sed-i's/\.html/\.php/g'{}

它将查找当前目录和子目录中以
.html
结尾的所有文件,并在每个文件上运行
sed
,以将
.html
替换为
.php


有关更多详细信息,请参阅。

在我的Mac电脑上,我必须向
-I
选项添加一个参数:要添加到名称的扩展名(在本例中,没有任何内容,因此文件存储在适当的位置)

来源:

这对我来说很有效:


find-在下面的脚本中键入f-print0 | xargs-0 sed-i's/str1/str2/g'

有助于替换文件中的字符串:

#!/bin/bash
echo -e "please specify the folder where string has need to be replaced: \c"
read a
echo -e "please specify the string to be replaced: \c"
read b
echo -e "please specify the string: \c"
read c
find $a -type f -exec sed -i 's/'"$b"'/'"$c"'/g' {} \; > /dev/null 2>&1
if [ $? -eq 0 ]
then
echo "string has been replaced..."
else                                                                         echo "String replacement has been failed"
exit0
fi

这适用于GNU
sed
;由于
sed
的非标准
-i
选项,@JonathanLeffler:是的,我们被宠坏了。:-)此解决方案在OSX上保留了文件结尾换行符,sed将在其中删除这些换行符。(但我必须
brew安装ack
find . -name '*.html' -exec sed -i '' 's/\.html/\.php/g' "{}" \;
You can certainly use ack to select your files to update. For example,
to change all "foo" to "bar" in all PHP files, you can do this from 
the Unix shell: 

perl -i -p -e's/foo/bar/g' $(ack -f --php)
#!/bin/bash
echo -e "please specify the folder where string has need to be replaced: \c"
read a
echo -e "please specify the string to be replaced: \c"
read b
echo -e "please specify the string: \c"
read c
find $a -type f -exec sed -i 's/'"$b"'/'"$c"'/g' {} \; > /dev/null 2>&1
if [ $? -eq 0 ]
then
echo "string has been replaced..."
else                                                                         echo "String replacement has been failed"
exit0
fi