WhS4
WhS4

Reputation: 103

Issue with sed command in Bash for string replacement

I've been looking for a way to find-and-replace strings in all fortran files in my current directory. Most answers on here are along the lines of using:

sed -i 's/INCLUDE \'atm/params.inc\'/USE params/g' *.f

or

perl -pi -w -e 's/INCLUDE \'atm/params.inc\'/USE params/g' *.f

However, when I use either of these the bash line continuation > pops up on the next line as if it's expecting input or another argument. I haven't seen anyone else encounter this and I am not sure what to do with it. Are my commands incorrect; am I missing something?

Upvotes: 0

Views: 166

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295262

There are two problems with the original:

  • You weren't protecting your / in the literal data from being parsed by sed rather than treated as data. One very readable and explicit way to do this is with [/].
  • You were trying to use \' to put a literal ' in a single-quoted string. That doesn't work. The common idiom is '"'"', which, character-by-character, does the following:

    1. ' - exits the original single-quoted context
    2. " - opens a double-quoted context
    3. ' - adds a literal single-quote (protected by the surrounding double quotes)
    4. " - ends that double-quoted context
    5. ' - resumes the outer single-quoted context.

Thus, consider:

# note: this works with GNU sed, not MacOS sed or others
sed -i 's/INCLUDE '"'"'atm[/]params.inc'"'"'/USE params/g' *.f

Upvotes: 4

Related Questions