Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get string between "-(" and ")-", linux directory

i have in a linux directory a lot of files, plain text with some directories, and i want to search in all those files and get the exactly the string between "-(" and ")-" like:

bbbfb da bg -(fdsd)- fgfjmui -( juju gfdgf b)- fsdf sdfs dsfdlk,kwwk
xwpv -(64fsdfds)- fsdfsd -(a)- fsdfsd...

and return:

  • fdsd
  • juju gfdgf b
  • 64fsdfds
  • a ...

i read for a while, and i found commands like grep, but i tried and i think that command return the exactly string and just one by line:

grep -Rn "-(" *

i tried also sed command like:

sed -e 's/.*-(\([^"]*\))-.*/\1/'

which return all the lines and where is the pattern, only the string inside -( and )-, but is not quite right yet.

i read about awk, but my question is: is possible with grep, sed or awk? there some more things to put on sed command? (i'm kinda new on this) there is another command to do this? or the other idea i was thinking is make a little c program to read files char by char

like image 375
armandfp Avatar asked Jun 05 '26 17:06

armandfp


2 Answers

grep -RPo '(?<=-\()[^)]*(?=\)-)' yourDir

this will give you the strings you want each per line

test with your example:

kent$  echo "bbbfb da bg -(fdsd)- fgfjmui -( juju gfdgf b)- fsdf sdfs dsfdlk,kwwk xwpv -(64fsdfds)- fsdfsd -(a)- fsdfsd..."|grep -Po '(?<=-\()[^)]*(?=\)-)'
fdsd
 juju gfdgf b
64fsdfds
a

the trick here is "o": from man page of grep:

-o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

like image 86
Kent Avatar answered Jun 08 '26 09:06

Kent


Use ack:

ack -o -h '(?<-\().*?(?:\)-)'

Details of the regex:

(?<-\() : lookbehind assertion : dash and opening parenthese
.*? : as few characters as possible
(?:\)-) : lookahead assertion : closing parenthese and dash.

If your files don't come use the -a switch for unrestricted search. Program options avail in the given link.

like image 32
Benoit Avatar answered Jun 08 '26 08:06

Benoit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!