Replace a string before a certain line

I have one file like:

ID_SOUR_CALENDAR BIGINT NOT NULL DEFAULT 0  COMPRESS 0 ,
UNIQUE PRIMARY INDEX ( CALENDAR_DATE );
ID ,
ID_SOUR ,
PRIMARY INDEX ( CALENDAR_DATE );

I want to replace the ‘,’ by ‘)’ in the line just before the line containing PRIMARY.

The result should be:

ID_SOUR_CALENDAR BIGINT NOT NULL DEFAULT 0  COMPRESS 0 )
UNIQUE PRIMARY INDEX ( CALENDAR_DATE );
ID ,
ID_SOUR )
PRIMARY INDEX ( CALENDAR_DATE );

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Using GNU sed:

sed  'N;s/,\(\s*\n.*PRIMARY\)/)\1/;P;D' file

ID_SOUR_CALENDAR BIGINT NOT NULL DEFAULT 0  COMPRESS 0 )
UNIQUE PRIMARY INDEX ( CALENDAR_DATE );
ID ,
ID_SOUR )
PRIMARY INDEX ( CALENDAR_DATE );
  • N Read/append the next line of input into the pattern space.
  • P Print up to the first embedded newline of the current pattern space.
  • D Delete up to the first embedded newline in the pattern space. Start next cycle, but skip reading from the input if there is still data in the pattern space.

Solution 2

Try reversing the file, doing the string replacement on the line after PRIMARY, then re-reversing the file:

tac file | sed '/PRIMARY/ {n; s/,$/)/}' | tac

Solution 3

try this,

perl -0777 -pe 's/,([^\n,]*\n[^\n]*PRIMARY)/)$1/g'

This will replace the last , with ) in lines before any line including PRIMARY.

Explanation

  • perl -0777 slurp whole file (read as one line)
  • s/search_pattern/replacement/g Substitute search pattern with replacement globally

Solution 4

If you use ed rather than sed you can use a regex address with negative offset:

g/PRIMARY/-1 s/,$/)/

Ex.

$ printf 'g/PRIMARY/-1 s/,$/)/\n,p\nq\n' | ed -s file
ID_SOUR_CALENDAR BIGINT NOT NULL DEFAULT 0  COMPRESS 0 )
UNIQUE PRIMARY INDEX ( CALENDAR_DATE );
ID ,
ID_SOUR )
PRIMARY INDEX ( CALENDAR_DATE );

or (for in-place editing)

printf 'g/PRIMARY/-1 s/,$/)/\nwq\n' | ed -s file

The replacement will match ALL instances of /PRIMARY/ – if you only want to replace the first, remove the g modifier.

Solution 5

With POSIXly sed you can do the following:

sed -e '
    /PRIMARY/!{x;1!p;d;}
    x;s/,/)/;$G
' input-file.txt

Output:

ID_SOUR_CALENDAR BIGINT NOT NULL DEFAULT 0  COMPRESS 0 )
UNIQUE PRIMARY INDEX ( CALENDAR_DATE );
ID ,
ID_SOUR )
PRIMARY INDEX ( CALENDAR_DATE );

Working:

  • For non-PRIMARY lines, we save the line and print the one we saved in the hold.
  • And for the PRIMARY, we retrieve the previous and effect the transformation.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply