0

I have to write short script to replace line in file. Some of the lines contains slashes and left square brackets (probably right also).

I know that another delimiter should be used to replace line with slashes.

My code:

sed -i -e "s|${oldLine}|${newLine}|g"

This throws an error because line contains [.

Example String in line to change (oldLine variable):

// List exampleList = [

Example how like should look after change:

List exampleList = [

How to make it works when there are some chars like [

To reproduce:

sed -i -e 's|// List exampleList = [|List exampleList = [|g' test.txt
Chris
  • 652
  • 1
  • 7
  • 22
  • 1
    Please add your desired output for that sample input to your question. – Cyrus May 28 '19 at 17:59
  • @Cyrus Example added – Chris May 28 '19 at 18:01
  • Please add your **desired output** for that sample input to your question. – Cyrus May 28 '19 at 18:06
  • @Cyrus I don't fully understand what you need. There is an example what is passed to that script as oldLine and newLine – Chris May 28 '19 at 18:10
  • Without putting too fine a point on it .. Can't you simply remove the bracket in the variable .. OR escape it prior to `sed` IE `\[` ? -- It seems to me that `// List exampleList =` should be *plenty* for a search replace .. Is there a reason you have to include the bracket? – Zak May 28 '19 at 18:10
  • @Zak I can't remove it. i.e. if there will be line like // List exampleList = [someValue, and if i will remove bracket it will execute something like: sed -i -e 's|// List exampleList = someValue,|List exampleList = someValue|g' test.txt . It will be not replaced – Chris May 28 '19 at 18:14
  • Can you use `PERL` It would be far simpler .. IE `perl -p -e 's/$ENV{SearchVar}/$ENV{ReplaceVar}/g' test.txt` ? – Zak May 28 '19 at 18:16
  • If you weren't using variables, you would have to write `sed -i -e 's|// List exampleList = \[|List exampleList = \[|g' test.txt`. As you are using variables, you need to ensure that the variables contain valid snippets of `sed` so that after expansion, the argument is a complete, valid `sed` script. `sed` itself doesn't take parameters and can't do the escaping for you. – chepner May 28 '19 at 21:54

1 Answers1

0

You need to escape the "bad" characters in $oldline and $newline. The command

sed -e 's/\\/\\\\/g; s/\([[&()/\]]\)/\\\1/g'

will replace \,[,&,(,),/,] with \\,\[, etc. So the combined command

sed -e "s/$(echo $oldline | sed -e 's/\\/\\\\/g; s/\([[&()/\]]\)/\\\1/g')/$(echo $newline | sed -e 's/\\/\\\\/g; s/\([[&()/\]]\)/\\\1/g')/g"

will do what you want.

LaszloLadanyi
  • 973
  • 4
  • 12