简体   繁体   English

在linux中搜索和替换文件(sed)

[英]search and replace files in linux(sed)

I'm trying to search and replace the following: 我正在尝试搜索并替换以下内容:

<?php 
<!DOCTYPE HTML>

with

<!DOCTYPE HTML>

so far I have tried this: 到目前为止我试过这个:

find . \( -name "*.php" \) -exec grep -Hn "<?php <\!DOCTYPE HTML>" {} \; -exec sed -i 's/<?php <\!DOCTYPE HTML>/<\!DOCTYPE HTML>/g' {} \;

But it's not finding any instances of files with my needle string which exists on my server. 但它没有找到我的服务器上存在的带有针串的文件的任何实例。

find . -name "*.php" -exec grep -lZz '^<?php[[:space:]]\+<!DOCTYPE HTML>' {} + |
xargs -r0 sed -i '^<?php[[:space:]]*$/,1d'

Edit: The previous version didn't work due to the character \\n in the pattern. 编辑:由于模式中的字符\\n ,以前的版本无法正常工作。 The updated version avoid this character. 更新版本避免使用此字符。

With GNU awk (for RS='\\0' to read the whole file as one record) and assuming your file names don't contain newlines all you need is the clear, simple: 使用GNU awk(对于RS='\\0'将整个文件作为一个记录读取)并假设您的文件名不包含换行符,您只需要清楚,简单:

find . -name '*.php' -print |
while IFS= read -r file; do
    gawk -v RS='\0' '{gsub(/<\?php\n<!DOCTYPE HTML>/,"<!DOCTYPE HTML>"); print}' "$file" > tmp &&
    mv tmp "$file"
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM