1

I want to insert a word at the beginning of a line specified with line number, using sed. This oneliner works:

line="this is my line"; newfile=`sed "6s/.*/word $line/" /opt/file.txt`

But my issue is that when i run the code in a script it throws an error:

line="this is my line"
newfile=`sed "6s/.*/word $line/" $FILE_PATH`
sed: -e expression #1, char 91: unknown option to `s'

Sed version: GNU sed version 4.1.5

kapten1
  • 9
  • 1
  • In script also it is working – Karthikeyan.R.S Mar 18 '16 at 09:55
  • 3
    Are you sure you are just doing exactly what you said (ie: the value of `$line` does not contain special characters)? It should work. Note if you want to prepend the line and not replace it, it should be: `sed "6s/^/word $line/"` – bufh Mar 18 '16 at 09:57
  • You should double quote your FILE_PATH var : `"$FILE_PATH"`. – SLePort Mar 18 '16 at 10:01
  • @bufh You are right, I edited `$line` for readability, and it does actually contain a bracket [, which is char 91. Can I escape the bracket from the command without editing the `$line` ? – kapten1 Mar 18 '16 at 10:02
  • @bufh I used your prepend syntax instead and it works perfectly, thank you! =) – kapten1 Mar 18 '16 at 10:09
  • I would redirect you to the solutions proposed on this thread: http://stackoverflow.com/questions/407523/escape-a-string-for-a-sed-replace-pattern; you would do something like: `line=$(echo "$line|sed 's/[]\/$*.^|[]/\\&/g')` before using it. – bufh Mar 18 '16 at 10:10

1 Answers1

1

Seems like you have some symbols in $line and sed can't work with them without escaping it. Char 91 is "["

Try this:

line='this is my line'
newfile=`sed "6s/.*/word $line/" $FILE_PATH`

or this

line="this is my line"
newfile=`sed '6s/.*/word '$line'/' $FILE_PATH`

maybe it will help

GRbit
  • 39
  • 7