Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save part of matching pattern to variable

I want to extract a substring matching a pattern and save it to a file. An example string:

Apr 12 19:24:17 PC_NMG kernel: sd 11:0:0:0: [sdf] Attached SCSI removable disk

I want to extract the part between the brackets, in this case [sdf].

I tried to do something like grep -e '[$subtext]' to save the text in the brackets to a variable. Of course it doesn't work, but I am looking for a way similar to this. It would be very elegant to include a variable in a regex like this. What can I do best?

Thanks!

like image 224
Ben Ruijl Avatar asked Apr 12 '10 18:04

Ben Ruijl


People also ask

What is pattern matching syntax?

The pattern-matching algorithm uses a variety of techniques to match different kinds of expression. Data elements such as numbers, strings, booleans are matched by comparison: a pattern consisting of a single data element matches only that exact element.

What is pattern matching in Unix?

Pattern matching in the shell against filenames has metacharacters defined differently from the rest of unix pattern matching prgorams. * is match any character except whitespace, ? is match one character except whitespace. so *. c is match any filename ending with the two characters .

How do you're match in Python?

match() function of re in Python will search the regular expression pattern and return the first occurrence. The Python RegEx Match method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object.


1 Answers

sed is greedy, so the sed answers will miss out some of the data if there are more [] pairs in your data. Use the grep+tr solution or you can use awk

$ cat file
[sss]Apr 12 19:24:17 PC_NMG kernel: sd 11:0:0:0: [sdf] Attached SCSI removable disk [tag] blah blah

$ awk -F"[" '{for(i=2;i<=NF;i++){if($i~/\]/){sub("].*","",$i)};print $i}}' file
sss
sdf
tag
like image 110
ghostdog74 Avatar answered Sep 30 '22 17:09

ghostdog74