Home > front end >  Sed replace using variable containing " or /
Sed replace using variable containing " or /

Time:01-25

I have a file containing includes.

BASE_FILE :

#include "File1.hpp"
#include "Rep/File2.hpp"

I want to add these includes in another file (NEW_FILE). I wrote a script :

grep "$BASE_FILE" - "#include" | while read -r INC
  if ! grep -q "$INC" "$NEW_FILE"
  then
    sed -i "1s/^/$INC/g" "$NEW_FILE"
  fi
done

But I have error "wrong option for s". I don't know if my problem comes from the " or the / in my BASE_FILE.

CodePudding user response:

We can avoid looping and running expensive grep sed for each matching line inside the loop.

You can use grep to give you missing include lines from the new file using:

grep -vFf "$new_file" <(grep -F '#include' "$base_file")

Once you get this difference it is straight forward to add these lines at the top:

{
grep -vFf "$new_file" <(grep -F '#include' "$base_file")
cat "$new_file"
} > _tmp &&
mv _tmp "$new_file"

Note that I have avoided using all uppercase variables to avoid potential conflict with reserved environment variables in shell.

  • Related