Bash (could potentially use perl / python): a list of arguments with limited space for a filter using regular expressions

I have a set of regular expressions that should be tested against every item in a list with space separators.

I want these elements to have spaces in them that will be escaped. So:

abc def\ ghi jkl abc 

consists of 4 elements, abc , def ghi , jkl and abc .

If my set of regular expressions

 b k$ ^g 

the conclusion should be

 abc abc 

It seems that grep -f can get most of the way from me, but I need to deal with handling escaped spaces, so I can't just make tr from space to a new line.

Edit: I think I could just use sed to replace regular spaces with strings with escaped space. And tr enough on the way back from newlines. I wonder if anyone has any better ideas.

+4
source share
2 answers

I really do not understand how your data is indicated.

Pretending that they come from the conclusion of the secret of the program, in one line, for example,

 gniourf@somewhere $ mystery abc def\ ghi jkl abc 

you can (myscript file):

 #!/bin/bash output=() re=( 'b' 'k$' '^g' ) # array of your regexes read -aa for w in "${a[@]}"; do for r in "${re[@]}"; do if [[ $w =~ $r ]]; then output+=( "${w// /\\ }" ) # replace space with backslash-space break fi done done echo "${output[@]}" 

For testing purposes, I did the following:

 #!/bin/bash # file mystery echo 'abc def\ ghi jkl abc' 

Then (after chmod +x mystery myscript ):

 gniourf@somewhere $ ./mystery abc def\ ghi jkl abc gniourf@somewhere $ ./mystery | ./myscript abc abc 

Caveat. It will break sooner or later, unless the secret discovers decent material!

+1
source

I think that it can be processed in bash on its own without any external utility.

First put your lines in an array:

 input=(abc 'def ghi' jkl abc) 

Then run this for loop to check your input with the regex provided:

 for i in "${input[@]}"; do for r in 'b' 'k$' '^g'; do [[ "$i" =~ $r ]] && echo $i && break done done 

Outout:

 abc abc 
+2
source

Source: https://habr.com/ru/post/1487636/


All Articles