Reputation: 55
I need to append two words before each match lines -
have following text file -
demo.txt -
Good
70 80 75 77 82
Best
Fail
34 32 30 24 29
What I am looking for is, if it find Good it should append 2 words before it like below - Good
(sysdate) Good 70 80 75 77 82
and if no record found, should not do anything like with Best record as there's no record so no need to append (sysdate) Best in front of it's line.
but trick here is, it should check two conditions, first status as Good, Best or Fail status from file and second if associate record is blank then no need to append anything.
below is short code of shell script -
#!/bin/bash
TIME=`date +"%Y-%m-%d %H:%M:%S"`
log="demo.txt"
for line in $log
do
if $line eq 'Good'; then
sed "/$line/!p s/[[:space:]]\+$//g" $log | sed "s/^/$TIME,Good /g" $log | sed 's/ /,/g' $log > demo.csv
elif $line eq 'Best'; then
sed "/$line/!p s/[[:space:]]\+$//g" $log | sed "s/^/$TIME,Best /g" $log | sed 's/ /,/g' $log > demo.csv
else
sed "/$line/!p s/[[:space:]]\+$//g" $log | sed "s/^/$TIME,Fail /g" $log | sed 's/ /,/g' $log > demo.csv
fi
done
Note :- looking for below output to csv file -
demo.csv -
Good
(sysdate),Good,70,80,75,77,82
Best
Fail
(sysdate),Fail,34,32,30,24,29
Upvotes: 2
Views: 136
Reputation: 16997
Input
$ cat demo.txt
Good
70 80 75 77 82
Best
Fail
34 32 30 24 29
Output
$ awk -v OFS="," 'NF==1{ print; s=$0; next}{$1=$1; print "(sysdate)",s,$0}' demo.txt
Good
(sysdate),Good,70,80,75,77,82
Best
Fail
(sysdate),Fail,34,32,30,24,29
With datetime
$ awk -v t="$(date +'%Y-%m-%d %H:%M:%S')" -v OFS="," 'NF==1{ print; s=$0; next}{$1=$1; print t,s,$0}' demo.txt
Good
2017-03-15 17:12:16,Good,70,80,75,77,82
Best
Fail
2017-03-15 17:12:16,Fail,34,32,30,24,29
With gawk
$ awk -v OFS="," 'BEGIN{t=strftime("%Y-%m-%d %H:%M:%S",systime())}NF==1{ print; s=$0; next}{$1=$1; print t,s,$0}' demo.txt
Good
2017-03-15 17:18:50,Good,70,80,75,77,82
Best
Fail
2017-03-15 17:18:50,Fail,34,32,30,24,29
Explanation
awk -v OFS="," ' # call awk set o/p field separator as comma
BEGIN{ # Begin block here we save system datetime in variable t and is gwak specific
t=strftime("%Y-%m-%d %H:%M:%S",systime())
}
NF==1{ # if no of fields/columns is equal to 1 then
print; # print current record/line/row
s=$0; # save current line in variable s
next # stop processing go to next line
}
{
$1=$1; # record recompilation
# since you need comma as separator between fields in o/p,
# you can also do $2=$2
# assigning any value to any field ($1, etc.)
# causes record recompilation
print t,s,$0 # print variable t, s and current line
}' demo.txt
Upvotes: 1