Search code examples
regexawksedgrepxargs

Search and Replace String from text file Ubuntu


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.


Solution

  • 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 \)