I am working on a file which has entries as follows. I am using while read line to generate desired output as follows.
filename1:
Name : sdt2156157_ID
NOS : 4567 [ sdt2156157/67 ]
NOS : 2348 [ sdt2156157/48 ]
Name : sdt2156158_ID
NOS : 4987 [ sdt2156158/87 ]
NOS : 2332 [ sdt2156158/32 ]
while read line
do
nos=$(echo $line|grep NOS|awk '{print $3}')
name=$(echo $line|awk '{ if ($1 == "Name") print $5}')
echo $name
echo "INSERT -name $name -nos $nos to chart ABC;"
done < filename1
However I get following o/p.
sdt2156157_ID
INSERT -name mdt2156157_ig -nos to chart ABC;
INSERT -name -nos 4567 to chart ABC;
INSERT -name -nos 2348 to chart ABC;
Desired O/P is as follows.
sdt2156157_ID
INSERT -name mdt2156157_ig -nos 4567 to chart ABC;
INSERT -name mdt2156157_ig -nos 2348 to chart ABC;
Please guide me how can I save value from earlier line.
Here are two solution, using pure ksh/bash or awk, not mixed.
#!/usr/bin/someposixshell ksh, bash, dash, ...
# make tmp file for input
cat <<EOF > $0.tmp
Name : sdt2156157_ID
NOS : 4567 [ sdt2156157/67 ]
NOS : 2348 [ sdt2156157/48 ]
Name : sdt2156158_ID
NOS : 4987 [ sdt2156158/87 ]
NOS : 2332 [ sdt2156158/32 ]
EOF
# ver 1 using shell
# set fld delimiter
IFS="${IFS}:]["
name=""
action="INSERT"
while read key id value x
do
case "$key" in
Name) name="$id" ; echo $name ; action="INSERT" ;;
NOS) echo "$action -name $name -nos $id to chart ABC;" ; action="APPEND";;
esac
done < $0.tmp
# ver 2 using awk
awk '
$1 == "Name" { name=$3 ; print name ; action="INSERT"; next }
$1 == "NOS" {
print action," -name ",name," -nos",$3," to chart ABC;"
action="APPEND"
}
' $0.tmp
rm -f $0.tmp 2>/dev/null
Wonderful !!! Thank you kshji. Appreciate your prompt response.
---------- Post updated at 02:26 PM ---------- Previous update was at 12:51 PM ----------
Actually I should have mentioned following O/P. Note APPEND in place of insert everyline after First in one Name record. Any help would be appreciated.
sdt2156157_ID
INSERT -name mdt2156157_ig -nos 4567 to chart ABC;
APPEND -name mdt2156157_ig -nos 2348 to chart ABC;