Regex, select the line that starts with my condition, but take only the characters after space

Viewed 195

I have a file that has content similiar below:

ptrn: 435324kjlkj34523453
Note1: rtewqtiojdfgkasdktewitogaidfks
Note2: t4rwe3tewrkterqwotkjrekqtrtlltre

I am trying to get characters after space at the line starts with "ptrn:" . I am trying the command below ;

>>> cat daily.txt | grep '^p.*$' > dailynew.txt

and I am getting the result in the new file:

ptrn: 435324kjlkj34523453

But I want only the characters after space, which are " 435324kjlkj34523453" to be written in the new file without "ptrn:" at the beginning.

So result should be like:

435324kjlkj34523453

How can establish this goal with the efficient regex code?

2 Answers

You can use

grep -oP '^ptrn:\s*\K.*' daily.txt > dailynew.txt
awk '/^ptrn:/{print $2}' daily.txt > dailynew.txt
sed -n 's/^ptrn:[[:space:]]*\(.*\)/\1/p' daily.txt > dailynew.txt

See the online demo. All output 435324kjlkj34523453.

In the grep PCRE regex (enabled with -P option) the patterns match

  • ^ - the startof string
  • ptrn: - a ptrn: substring
  • \s* - zero or more whitespaces
  • \K - match reset operator that clears the current match value
  • .* - the rest of the line.

In the awk command, ^ptrn: regex is used to find the line starting with ptrn: and then {print $2} prints the value after the first whitespace, from the second "column" (since the default field separator in awk is whitespace).

In sed, the command means

  • -n - suppresses the default line output
  • s - substitution command is used
  • ^ptrn:[[:space:]]*\(.*\) - start of string, ptrn:, zero or more whitespace, and the rest of the line captured into Group 1
  • \1 - replaces the match with group 1 value
  • p - prints the result of the substitution.

You can use this sed:

sed -nE 's/^ptrn: (.*)/\1/p' file > output_file.txt
Related