Search code examples
bashawkgreptext-parsing

How to remove a block of known lines (an entire function) from a script using bash...?


How would you remove a known part of a file, for example the one below:

func1() {
  # some code with conditions
  if [...]; then...
  # with some new lines too

  # some code again
}

from a script file?

I tried this way:

grep -xvF "$(cat <<'HEREDOC'
func1() {
  # some code with conditions
  if [...]; then...
  # with some new lines too

  # some code again
}
HEREDOC
)" file > ouput

It works, except that it removes any new line. I haven't found a way of sorting this out. I made an attempt with awk but it was throwing syntax errors on the brackets and = signs found in the block. The examples I found on StackExchange platforms generally try to remove several lines by pattern. Does someone have a way of achieving this being able to deal with the special characters and keeping the output file similar to what it was before?


Solution

  • Using GNU sed:

    sed -z -f <(sed 's|[.*^$/\[]|\\&|g; s|$|\\n|; 1s|^|s/|; $a //g' delete.txt | tr -d '\n') file
    

    The delete.txt contains the contiguous portion that is to be removed from the file