1

I have a few CmakeLists.txt files and I would like to insert another include right after a known include. So, here's what I've got:

include_directories(src include)

And, here's what I would like to end up with

include_directories(src include)
include_directories("${CMAKE_INSTALL_PREFIX}/include")

Any ideas on the best way to do this? I'm assuming sed would make the most sense, but I'm open to alternatives.

[edit] Found a duplicate question.

Community
  • 1
  • 1
bitcycle
  • 7,094
  • 13
  • 64
  • 116

4 Answers4

1

You can use this simple sed command with inline editing:

sed -i.bak '/include_directories(src include)/a\
include_directories("${CMAKE_INSTALL_PREFIX}/include")
' CmakeLists.txt
  • This uses a command which appends a new string after searched string.
  • -i.bak is for incline editing of the input file.
anubhava
  • 664,788
  • 59
  • 469
  • 547
0

If you're not satisfied with the answer to the duplicate question, you could try this:

sed '/include_directories(src include)/s/$/\
include_directories(\"${CMAKE_INSTALL_PREFIX}\/include\")/' filename

This might or not work, depending on your shell. If it doesn't, the lesson is to attempt simple things first, then build up.

Beta
  • 86,746
  • 10
  • 132
  • 141
0

sed is an excellent tool for simple substitutions on a single line but for anything else you're better off with awk:

awk '{print} /include_directories\(src include\)/{print "include_directories(\"${CMAKE_INSTALL_PREFIX}/include\")"}' file
Ed Morton
  • 157,421
  • 15
  • 62
  • 152
0

Another awk variation:

awk '/include_directories\(src include\)/{$0=$0 "\ninclude_directories(\"${CMAKE_INSTALL_PREFIX}/include\")"}8' file

If pattern found, add a new line to current line, then print all.

Jotne
  • 38,154
  • 10
  • 46
  • 52