2

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?

3
  • Welcome to SO, could you please post more clear samples of your Input and expected output in your post inside CODE TAGS and let us know then. Commented Oct 19, 2019 at 12:40
  • It's not clear what output you desire. You seem to be looking for sed backreferences; briefly, & lets you recall the entire matched string, and \1, \2 etc backslash-parenthesized subexpressions from the match. You also seem to need a thorough refresher on the shell's quoting facilities. Commented Oct 19, 2019 at 12:41
  • I'm sorry for being unclear, I'm trying to for example change #include <header.h> to #include <prefix/header.h> Commented Oct 19, 2019 at 12:44

2 Answers 2

1

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, & to match the regex was what I was looking for :)
You're welcome. Welcome to SO. If an answer solves your question, please accept it (you'll get 2 reputation points). If any answer was helpful, you can upvote it (once you have enough reputation).
1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.