1

My file looks like this:

record=123
date=2012.01.20 10:22

In the bash file I do cat myfile.ini, and then I need to use something like explode, because I need ONLY to grep the 123 numeric record data, and nothing else.

How it can be done in the bash ?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Cyclone
  • 14,839
  • 23
  • 82
  • 114

4 Answers4

4
awk -F'=| ' '/record/ {print $2}'

Substitute "date" for "record" in the command above to get the date (the time would be in $3).

This keys on the names of the variables rather than depending on a regex match of the value. It uses spaces or equal signs as field separators.

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
  • Nice one, but it doesn't work if there is a white space in the record (or date). fe: `record= 1` or `date=2012-01-20 16:30`. – Cyclone Jan 20 '12 at 15:30
  • @Cyclone: I describe the case where there is a date and time separated by a space (as shown in the question). It is true that it would fail if the input file is not "well formed". If you want the date and time together, you can use `-F'='`. – Dennis Williamson Jan 20 '12 at 15:36
3

If you have control over the ini file, rewrite it as:

record=123
date="2012.01.20 10:22"

Then in your "bash file" you do

. myfile.ini

echo $record

This is the typical approach. (if you have control over the ini file)

mvds
  • 45,755
  • 8
  • 102
  • 111
  • 1
    As long as you do have control over the file. Because in some cases this approach could be a security hazard (since any commands in the file would be executed). – theglauber Jan 20 '12 at 15:08
2

You can use:

#!/bin/sh
VALUE="`grep '^record=' myfile.ini |sed 's/[^0-9]//g'`"
xpapad
  • 4,376
  • 1
  • 24
  • 25
  • If there could be more than one "record=" line and you want the first one only, do _VALUE="`grep '^record=' myfile.ini | head -1 | sed 's/[^0-9]//g'`"_ – theglauber Jan 20 '12 at 15:10
  • Thanks, works fine, could you also tell me , how can I grep the date after the `date=` sign? – Cyclone Jan 20 '12 at 15:12
1

You can do something like this:

awk '/=[0-9]+$/' file.txt

to print only the line with numeric content after = sign on stdout.

However if you just want to capture 123 into a variable then you can use:

val=$(awk -F"=" '/=[0-9]+$/{print $2}' file.txt)
anubhava
  • 761,203
  • 64
  • 569
  • 643