Roozo
January 7, 2014, 1:46am
1
I have a below file
FILE.cfg
JAN_01
VAR1=4
VAR2=SUM
VAR3=PRIVATE
JAN_10
VAR1=44
VAR2=GUN
VAR3=NATUR
JAN_20
VAR1=3
VAR2=TQN
VAR3=COMMA
code: (JAN_10 is argument passed from script)
Var1=find_cfg(JAN_10)
Var2=find_cfg(JAN_10)
Var3=find_cfg(JAN_10)
find_cfg
{
awk '/JAN_10/ {for(i=1; i<=4; i++) {getline; print}}' FILE.cfg
}
The above awk command get's the next 4 lines, but how to get the related details and save like below ??
Var1=44
Var2=GUN
Var3=NATUR
You need the lines with 'VAR' alone in the output ?
if so just grep it.
What you mean by related details ?
What exactly you need in the output ?
Roozo
January 7, 2014, 2:25am
3
Argument passed to the script is JAN_10, using that search in the FILE.cfg file and getting next four lines from FILE.cfg,
say,
VAR1=44
VAR2=GUN
VAR3=NATUR
command line: script.sh JAN_10
script.sh:
#!/bin/ksh
function find_cfg
{
awk '/JAN_10/ {for(i=1; i<=3; i++) {getline; print}}' FILE.cfg
}
VAR1=find_cfg(JAN_10) #<---44
VAR2=find_cfg(JAN_10) #<---GUN
VAR3=find_cfg(JAN_10) #<---NATUR
Want to pass the values like highlighted according to argument passed to script
One of the way would be to source the file. Try
michaelf>cat fil.ksh
#!/bin/ksh
#function
find_cfg()
{
awk "/$1/ {for(i=1; i<=4; i++) {getline; print}}" FILE.cfg>/home/michael/outfil
}
#call the function
find_cfg JAN_10
#source the file
. /home/michael/outfil
#check the values
echo $VAR1
echo $VAR2
echo $VAR3
michaelf>chmod u+x fil.ksh
michaelf>./fil.ksh
44
GUN
NATUR
michaelf>
If the number of variables associated with different strings could vary, you might want to try:
awk -v string="$1" '
copy && $1 == "" { exit }
copy
$1 == string { copy = 1 }
' file
If you're using a Solaris/SunOS system, change awk
to /usr/xpg4/bin/awk
, /usr/xpg6/bin/awk
, or nawk
.
You can do like this no need to write to some file and source
$ cat file.cfg
JAN_01
VAR1=4
VAR2=SUM
VAR3=PRIVATE
JAN_10
VAR1=44
VAR2=GUN
VAR3=NATUR
JAN_20
VAR1=3
VAR2=TQN
VAR3=COMMA
$ cat querry.sh
#!/bin/ksh
file="file.cfg"
t_lines="4"
find_cfg(){
awk -v start="$1" \
-v stop="$t_lines" '
$0 == start{i=1;next}i{++i;print}i==stop{exit}' $file
}
find_cfg $1 | \
while read line; do
export $line && eval echo '$'${line%=*}
done
$ ksh querry.sh JAN_10
44
GUN
NATUR
RudiC
January 7, 2014, 4:07pm
7
Quite some ifs:
If I understand correctly that you want to define shell variables AND
if your file has really empty lines (yours above doesn't) separating records AND
if you know exactly, what you're doing when using the dangerous eval
,
try
eval $(awk '/^$/&&p {exit} p; /^JAN_10/ {p=1}' file
echo $VAR1
44