Search code examples
shellgrepcut

Cut specific words matching a pattern from a text file


I am trying to extract words from a text file matching a pattern using shell script. For example if a line contains

This is a sample text to illustrate my scenario text=info id=2342
Second line to illustrate text=sample id=q2312

I want the output to be like

text=info id=2342
text=sample id=q2312

Can somone please tell me how do i achieve it using cut/grep command?


Solution

  • You can do the following:

    grep -P -o 'text=\S+ id=\S+'

    The -P flag for grep enables the perl regular expression. \S+ will match all non blank space characters, -o outputs only the matched portion.

    Assuming you need to get the fields "text" and "id" values. Modify the regular expression as required. For perl regular expressions see here or extended regular expressions see man grep