Home > OS >  extract and display matching strings with similar pattern
extract and display matching strings with similar pattern

Time:01-14

I have an extremely long line. It contains a lot of strings with a similar patterns like below;

t[0-4]_vmdk_[a-z]_anything

t followed by a single digit with possible 0-4, and them '_vmdk_', and any long string with possible [a-z], then finally "_" in the end. The rest could be anything.

Ex:

asdfasfsa/_asdf**t2_vmdk_abc_**badfad**t3_vmdk_xyz_**asdfasdf**t1_vmdk_efg_**asbafdfb....

Please help me to display all such strings. Thank you!

CodePudding user response:

The simplest is probably with grep. If the input string comes from the standard output of another command (e.g. echo):

$ str='asdfasfsa/_asdf**t2_vmdk_abc_**badfad**t3_vmdk_xyz_**asdfasdf**t1_vmdk_efg_**asbafdfb....'
$ echo "$str" | grep -o 't[0-4]_vmdk_[a-z]*'
t2_vmdk_abc
t3_vmdk_xyz
t1_vmdk_efg

Explanation: the -o option prints "only the matched (non-empty) parts of a matching line".

If the input strings are stored in a file:

$ grep -o 't[0-4]_vmdk_[a-z]*' file.txt
t2_vmdk_abc
t3_vmdk_xyz
t1_vmdk_efg
  •  Tags:  
  • Related