Šaman Bobo
Šaman Bobo

Reputation: 75

Sed: adding a substring in the middle of a variable

I'm trying to change the directory of all C headers like #include "library.h" to #include "prefix/library.h" in a file using the sed command, but I can't figure out how to add a prefix to the middle of a string. So far I've tried this command:

sed -i "s"\/'#include[[:space:]]*[<"][^>"]*[>"]'\/"$prefix"\/ $filename

but it replaces the whole string instead of creating #include "prefix/library.h". Is there any way to change it while keeping the original #include, <, " and spacing?

Upvotes: 2

Views: 554

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133518

Could you please try following.

sed 's/\([^"]*\)\(\"\)\(.*\)/\1\2prefix\/\3/'  Input_file

Output will be as follows.

#include "prefix/library.h"


In case you have a shell variable then try following.

prefix="prefix"
sed "s/\([^\"]*\)\(\"\)\(.*\)/\1\2$prefix\/\3/" Input_file

Where your Input_file is as follows:

cat Input_file
#include "library.h"

Upvotes: 1

Chris Maes
Chris Maes

Reputation: 37742

you could use this:

sed "s%#include[[:space:]]*[<\"]%&$prefix/%" $filename

explanation:

  • You can use any separator with sed, I use % as a separator, to avoid trouble with / inside your filename
  • & means: the whole matched regex. To this way the pattern you just matched is printed again.
  • this command searches for #include " and adds the $prefix just after that match.

Upvotes: 1

Related Questions