0

I have a text file of the following format:

Value1=some string-1
Value2=some string-2
Value3=some string-3
Value4=some string-4
Value5=some string-5
Value6=some string-6

If I need to find the value for Value6 and print out some string-6 how would I do that in SHELL script?

if grep -qs "Value6" Test.txt
then
  print some string-6
fi

How would I print some string-6 here?

Siddharthan Asokan
  • 4,321
  • 11
  • 44
  • 80

1 Answers1

0

The easy way is with grep and sed. Example:

grep Value6 file | sed -e 's/^.*[=]//'

Example Input

$ cat tmpf
Value1=some string-1
Value2=some string-2
Value3=some string-3
Value4=some string-4
Value5=some string-5
Value6=some string-6

Use/Output

$ grep Value6 tmpf | sed -e 's/^Value6[=]//'
some string-6

Note, you can also do this in a single set call:

$ sed -n 's/^Value6[=]//p' < tmpf
some string-6

Regardless which method you use, to save the resulting string to a variable, you can use command substitution

myvar=$(sed -n 's/^Value6[=]//p' < tmpf)

or the older (and now less used) backticks variant

myvar=`sed -n 's/^Value6[=]//p' < tmpf`
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • `sed` is a superset of `grep`; so this is a [useless use of `grep`](http://www.iki.fi/era/unix/award.html#grep). – tripleee Feb 17 '16 at 14:50
  • Also, without proper anchoring, this will extract nothing from `=Hello, this is Value6` and the wrong thing from `Value1=not at all like Value6` – tripleee Feb 17 '16 at 14:51
  • Yes, you are correct, but when you talk about solutions that *suppress pattern space* to folks who are just learning to parse, it sometimes makes their eyes roll back in their heads. I added the pure `sed` solution. – David C. Rankin Feb 17 '16 at 15:34
  • Is there a way I can save it to a variable? – Siddharthan Asokan Feb 17 '16 at 19:35
  • Sure `myvar=$(sed -n 's/^Value6[=]//p' < tmpf)` is all it takes. I'll add it to the answer. – David C. Rankin Feb 17 '16 at 21:14