Search and Replace String from text file Ubuntu

狂风中的少年 提交于 2019-12-08 11:33:26

问题


I have to replace following String

//@Config(manifest

with below string,

@Config(manifest

So this i created following regex

\/\/@Config\(manifest

And tried

grep -rl \/\/@Config\(manifest . | xargs sed -i "\/\/@Config\(manifest@Config\(manifest/g"

But i am getting following error:

sed: -e expression #1, char 38: Unmatched ( or \(

I have to search recursively and do this operation, though i am stuck with above error.


回答1:


grep -rl '//@Config(manifest' | xargs sed -i 's|//@Config(manifest|@Config(manifest|g'
  • Specifying . for current directory is optional for grep -r
  • sed allows Any character other than backslash or newline to be used as delimiter

Edit

If file name contains spaces, use

grep -rlZ '//@Config(manifest' | xargs -0 sed -i 's|//@Config(manifest|@Config(manifest|g'

Explanation (assumes GNU version of commands)

  • grep

    • -r performs recursive search
    • -l option outputs only filenames instead of matched patterns
    • -Z outputs a zero byte (ASCII NUL character) after each file name instead of usual newline
    • 'pattern' by default, grep uses BRE (basic regular expression) where characters like ( do not have special meaning and hence need not be escaped
  • xargs -0 tells xargs to separate arguments by the ASCII NUL character

  • sed

    • -i inplace edit, use -i.bkp if you want to create backup of original files
    • s|pattern|replace|g the g flag tells sed to search and replace all occurrences. sed also defaults to BRE and so no need to escape (. Using \( would mean start of capture groups and hence the error when it doesn't find the closing \)


来源:https://stackoverflow.com/questions/39218941/search-and-replace-string-from-text-file-ubuntu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!