0

I have a line in a text file that goes something like this s:Variable = "Path/to/file" but what I'm doing is replacing that line with a different 'newline' using a while loop in a bash script.

The way I'm doing this is by this command

sed -i '' '5s/.*/'$newline'/' Outputfile.txt

Where I'm replacing the fifth line in the Outputfile.txt with the $newline. I've tried all sorts of instances of "" and '' or using ${newline} but I can't seem to get it to work. It seems to be having an issue with the fact that the newline itself has quotation marks because I need to have those in new text file.

This is the newline that I have stored:

newline='s:Variabels = "Path/to/80kVp/NAME'${i}'_1"'

where the variable i is being looped through.

Any ideas of how to handle this?

Output Error: sed: 1: "5s/.*/s:Sc/DoseToCompon ...": bad flag in substitute command: 'D

D.Cecchi
  • 25
  • 3
  • `sed` is not the best choice of tools for the job. See the awk-based `gsub_literal` function in [BashFAQ #21](https://mywiki.wooledge.org/BashFAQ/021). – Charles Duffy Mar 20 '21 at 18:04
  • Thanks for the response! It seems actually that the issue at first is in the s:Variables part. The Variables end up being like this s:Sc/Dose/Component and it's saying the bad command is at the 'D'. Any ideas with that? Full disclosure, I have not attempted awk yet. – D.Cecchi Mar 20 '21 at 18:52
  • https://stackoverflow.com/questions/407523/escape-a-string-for-a-sed-replace-pattern – KamilCuk Mar 20 '21 at 19:04
  • 1
    I figured it out, the issue was my delimiter in sed. As I had '/' in the newline, I had to use a different symbol and chose '&' and it worked just fine! – D.Cecchi Mar 20 '21 at 19:27
  • Right; the nice thing about the proposed awk is that it has no delimiters at all, so the entire class of problem doesn't exist in the first place; there exists no character you can't use without escaping, because the data (both the part to search for and the part to replace) is passed out of band from the code. – Charles Duffy Mar 20 '21 at 20:31

1 Answers1

1

The problem here is only sligthly related to the quotation marks -- the error you are getting is because the replacement text you are getting from $newline contains / characters. That ends the sed s command at the first /, causing it to treat following characters as modifiers. Since D (the first character after the first /) is not a valid modifier, you get an error. The easiest fix would be to escape the / characters in the replacment text:

newline='s:Variabels = "Path\/to\/80kVp\/NAME'${i}'_1"'

another possibility (which only works in some versions of sed) is to use a different character to delimit the s command:

sed -i "5s|.*|$newline|" Outputfile.txt

which only works as long as the replacement text does not contain a |

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226