0

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.

A.Pissicat
  • 3,023
  • 4
  • 38
  • 93

1 Answers1

1

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Thanks for answer, I've try your solution but command `grep -vFf "$new_file" <(grep -F '#include' "$base_file")` give me nothing. My tmp file before move is the same as "$base_file" – A.Pissicat Jan 24 '23 at 08:45
  • Break it down. First test `grep -F '#include' "$base_file"` then `grep -vFf "$new_file" <(grep -F '#include' "$base_file")` commands and see if those are giving right outputs. – anubhava Jan 24 '23 at 10:17