简体   繁体   中英

search through regex pattern in a file

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.

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

You've been close; ;)

sed '/bit_top.*FDIO/d' input

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

Using sed

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

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 ie skip it. If that did not happen line is just print ed.

(tested in GNU Awk 5.0.1)

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM