0

I have a text file that carries the following values

Key 1: 0e3f02b50acfe57e21ba991b39d75170d80d98e831400250d3b4813c9b305fd801
Key 2: 8e3db2b4cdfc55d91512daa9ed31b348545f6ba80fcf2c3e1dbb6ce9405f959602

I am using the following grep command to extract value of Key 1

grep -Po '(?<=Key 1=)[^"]*' abc.txt

However, it doesn't seem to work.
Please help me figure out the correct grep command

My output should be:

0e3f02b50acfe57e21ba991b39d75170d80d98e831400250d3b4813c9b305fd801
meallhour
  • 13,921
  • 21
  • 60
  • 117

5 Answers5

3

A grep+cut solution: Search for the right key, then return the third field:

$ grep '^Key 1:' abc.txt | cut -d' ' -f3

Or, equivalently in awk:

$ awk '/^Key 1:/ { print $3 }' abc.txt
Kusalananda
  • 14,885
  • 3
  • 41
  • 52
2

Don't use grep to modify the matching string, that's pointless, messy, and non-portable when sed already does it concisely and portably:

$ sed -n 's/^Key 1: //p' file
0e3f02b50acfe57e21ba991b39d75170d80d98e831400250d3b4813c9b305fd801
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
1

If your version of grep doesn't support PCRE, you can do the same with sed, e.g.

$ sed -n '/^Key 1: [^"]/s/^Key 1: //p' file.txt
0e3f02b50acfe57e21ba991b39d75170d80d98e831400250d3b4813c9b305fd801

Explanation

  • -n suppress normal printing of pattern space

  • /^Key 1: [^"]/ find the pattern

  • s/^Key 1: // substitute (nothing) for pattern

  • p print the remainder

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
0

You have mistake in your grep (change Key 1= to Key 1:)

grep -Po '(?<=Key 1: )[^"]*' abc.txt
Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
0
grep -oP '(?<=Key 1: )[^"]+' abc.txt

seems to work for me.

twirlimp
  • 1
  • 2