meallhour
meallhour

Reputation: 15609

How to grep for a key in the file?

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

Upvotes: 0

Views: 1733

Answers (5)

Ed Morton
Ed Morton

Reputation: 204568

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

Upvotes: 2

Kusalananda
Kusalananda

Reputation: 15633

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

Upvotes: 3

David C. Rankin
David C. Rankin

Reputation: 84642

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

Upvotes: 1

twirlimp
twirlimp

Reputation: 1

grep -oP '(?<=Key 1: )[^"]+' abc.txt

seems to work for me.

Upvotes: 0

Krzysztof Krasoń
Krzysztof Krasoń

Reputation: 27516

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

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

Upvotes: 0

Related Questions