-1

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
  • 9,007
  • 13
  • 36
  • 72

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
  • 12,623
  • 3
  • 33
  • 46
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
  • 157,421
  • 15
  • 62
  • 152
0

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

grep -Po '(?<=Key 1: )[^"]*' abc.txt
Krzysztof Krasoń
  • 23,505
  • 14
  • 77
  • 102
0
grep -oP '(?<=Key 1: )[^"]+' abc.txt

seems to work for me.

twirlimp
  • 1
  • 2
0

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
  • 69,681
  • 6
  • 44
  • 72