Wednesday, December 29, 2021

[SOLVED] using Grep to output a string

Issue

When running a command I get an output that outputs a chart:

+---------+------------------------------------------------------+
| Key     | Value                                                |
+---------+------------------------------------------------------+
| Address | longstringofcharacters |
+---------+------------------------------------------------------+
| Name    | word1-word2-word3                              |
+---------+------------------------------------------------------+

I can grep Name to get the line that contains the word Name.

What do I grep to output just the string of word1-word2-word3 only?

I've tried grep '*-*-*' but that doesn't work.


Solution

With GNU grep, you can use a PCRE regex based solution like

grep -oP '^\h*\|\h*Name\h*\|\h*\K\S+' file

See the online demo and the regex demo.

  • -o - outputs matches only
  • P - enables the PCRE regex engine
  • ^ - start of string
  • \h*\|\h* - a | char enclosed with optional horizontal whitespaces
  • Name - a word Name
  • \h*\|\h* - a | char enclosed with optional horizontal whitespaces
  • \K - match reset operator that discards text matched so far
  • \S+ - one or more non-whitespace chars.

With a GNU awk:

awk -F'[|[:space:]]+' '$2 == "Name"{print $3}' file

Set the field separator to a [|[:space:]]+ regex that matches one or more | chars or whitespaces, check if Group 2 equals Name and grab Field 3.

With any awk (if you need to extract a string like nonwhitespaces(-nonwhitespaces)+):

awk 'match($0, /[^ -]+(-[^ -]+)+/) { print substr($0, RSTART, RLENGTH) }' file

See this online demo.



Answered By - Wiktor Stribiżew