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
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 |