简体   繁体   中英

How to exclude patterns in regex conditionally in bash?

This is the content of input.txt:

hello=123
1234
stack=(23(4))
12341234
overflow=345
=
friends=(987)

Then I'm trying to match all the lines with equal removing the external parenteses (if the line has it).

To be clear, this is the result I'm looking for :

hello=123
stack=23(4)
overflow=345
friends=987

I toughth in something like this:

cat input.txt | grep -Poh '.+=(?=\()?.+(?=\))?'

But does not returns nothing. What am I doing wrong? Do you have any idea to do this? I'm so interested.

Using awk:

awk 'BEGIN{FS=OFS="="} NF==2 && $1!=""{gsub(/^\(|\)$/, "", $2); print}' file
hello=123
stack=23(4)
overflow=345
friends=987

Here is an alternate way with sed :

sed -nr '              # Use n to disable default printing and r for extended regex 
/.+=.+/ {              # Look for lines with key value pairs separated by =
    /[(]/!ba;          # If the line does not contain a paren branch out to label a
    s/\(([^)]+)\)/\1/; # If the line contains a paren find a subset and print that
    :a                 # Our label 
    p                  # print the line
}' file

$ sed -nr '/.+=.+/{/[(]/!ba;s/\(([^)]+)\)/\1/;:a;p}' file
hello=123
stack=23(4)
overflow=345
friends=987

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