0

I'm setting variable $hack which I wish to expand and insert after the first line in a text file. The first line contains this text: project(libpyside)

Tried this:

$ sed -i "s|project(libpyside)|project(libpyside)\n$hack|" CMakeLists.txt
sed: -e expression #1, char 124: unterminated `s' command

...and this:

$ sed -i "/project(libpyside)/ r $hack" CMakeLists.txt
sed: -e expression #1, char 222: unknown option to `s'

...and this:

$ sed -i -e "2i${hack}" CMakeLists.txt
sed: -e expression #1, char 201: unknown option to `s'

This is my $hack variable:

hack='#HACK: CMake with broken Qt5Qml_PRIVATE_INCLUDE_DIRS, Qt5Quick_PRIVATE_INCLUDE_DIRS
if(${Qt5Qml_FOUND})
  if(NOT "${Qt5Qml_PRIVATE_INCLUDE_DIRS}" MATCHES "/QtQml/")
    string(REPLACE "/QtCore" "/QtQml" replaceme "${Qt5Core_PRIVATE_INCLUDE_DIRS}")
    list(APPEND Qt5Qml_PRIVATE_INCLUDE_DIRS ${replaceme})
    list(REMOVE_DUPLICATES Qt5Qml_PRIVATE_INCLUDE_DIRS)
  endif()
endif()
if(${Qt5Quick_FOUND})
  if(NOT "${Qt5Quick_PRIVATE_INCLUDE_DIRS}" MATCHES "/QtQuick/")
    string(REPLACE "/QtCore" "/QtQuick" replaceme "${Qt5Core_PRIVATE_INCLUDE_DIRS}")
    list(APPEND Qt5Quick_PRIVATE_INCLUDE_DIRS ${Qt5Qml_PRIVATE_INCLUDE_DIRS})
    list(APPEND Qt5Quick_PRIVATE_INCLUDE_DIRS ${replaceme})
    list(REMOVE_DUPLICATES Qt5Quick_PRIVATE_INCLUDE_DIRS)
  endif()
endif()'

What am I doing wrong?

The reason I'm not putting this into a file is I'm doing all of this from within a Dockerfile.

fredrik
  • 9,631
  • 16
  • 72
  • 132
  • this might be better than using variable... http://stackoverflow.com/questions/16715373/insert-contents-of-a-file-after-specific-pattern-match .. and `sed -i` twice is typo? – Sundeep Aug 19 '16 at 15:32
  • Typo fixed. `sed -i "/project(libpyside)/ r ${hack}" CMakeLists.txt` gives me `sed: -e expression #1, char 222: unknown option to \`s'` – fredrik Aug 19 '16 at 15:38
  • 1
    You have to make sure, that $hack contains a regular expression in Sed syntax. Your example shows that this is not the case. Your question is not how to expand, but how to quote. – ceving Aug 19 '16 at 15:44

2 Answers2

1

You will need to escape the newlines so it becomes:

sed 's|...|...\
...\
...|' CMakeLists.txt

One way is to use sed for it:

$ hack=$'hello\nworld'
$ sed '$!s/$/\\/' <<< "$hack"
hello\
world

And in your case it seems you might be able to use aafter instead of substitute:

$ hack=$(sed '$!s/$/\\/' <<< "$hack")
$ sed -i '/project(libpyside)/a'"$hack" CMakeLists.txt

If that is the case then use a process substitution and read instead:

$ sed -i '/project(libpyside)/'r<(printf "%s" "$hack") CMakeLists.txt
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
0

I would put the data into a file. Barring that, try:

echo "$hack" | sed '1r/dev/stdin' CMakeLists.txt

(Note that this inserts the data after the first line, and completely ignores the content of that line. From the wording of the question, that appears to be what you want.)

William Pursell
  • 204,365
  • 48
  • 270
  • 300