Home > Software design >  search through regex pattern in a file
search through regex pattern in a file

Time:01-31

I have a file with data in below format

abc {u_bit_top/connect_down/u_FDIO[6]/u_latch}
ghi {u_bit_top/seq_connect/p_REDEIO[9]/ff_latch
def {u_bit_top/connect_up/shift_reg[7]

I want to search for pattern *bit_top*FDIO* and *bit_top*REDEIO*in the file in each line and delete the complete line if pattern is found. I want output as

def {u_bit_top/connect_up/shift_reg[7]

I did using sed like sed "/bit_top/d;/FDIO/d;/REDEIO/d;" but this deletes the line having bit_top and FDIO and REDEIO separately. How I can search for above pattern and delete the line containing it. Shell or TCL anything will be useful.

CodePudding user response:

Since you tagged

set fh [open "filename"]
set contents [split [read -nonewline $fh] \n]
close $fh
set filtered [lsearch -inline -not -regexp $contents {bit_top.*(FDIO|REDEIO)}]

results in

def {u_bit_top/connect_up/shift_reg[7]

lsearch documentation.


But really all you need for this is

grep -Ev 'bit_top.*(FDIO|REDEIO)' filename

CodePudding user response:

You've been close! ;)

sed '/bit_top.*FDIO/d' input

Just input a regex to sed that matches what you want...

CodePudding user response:

Using sed

$ sed -E '/bit_top.*(REDE|FD)IO/d' input_file
def {u_bit_top/connect_up/shift_reg[7]

CodePudding user response:

You might use GNU AWK for this task following way, let file.txt content be

abc {u_bit_top/connect_down/u_FDIO[6]/u_latch}
ghi {u_bit_top/seq_connect/p_REDEIO[9]/ff_latch
def {u_bit_top/connect_up/shift_reg[7]

then

awk '/bit_top/&&(/FDIO/||/REDEIO/){next}{print}' file.txt

gives output

def {u_bit_top/connect_up/shift_reg[7]

Explanation: if lines contain bit_top AND (FDIO OR REDEIO) then go to next line i.e. skip it. If that did not happen line is just printed.

(tested in GNU Awk 5.0.1)

CodePudding user response:

With a small change you can implement the compound pattern (eg, *bit_top*FDIO*) in sed.

A couple variations on OP's current sed:

# daisy-chain the 2 requirements:

$ sed "/bit_top.*FDIO/d;/bit_top.*REDEIO/d" file
def {u_bit_top/connect_up/shift_reg[7]

# enable "-E"xtended regex support:

$ sed -E "/bit_top.*(FDIO|REDEIO)/d" file
def {u_bit_top/connect_up/shift_reg[7]
  • Related