Reputation: 43
date;
tocompdate=$(date --date="-90 days ago" +%d%m%Y)
echo $tocompdate;
awk -v pattern="$testdate" '{print "Some matter "nr[NR--]" matter "$testdate""};' tocompare.txt >> mail2sent.txt`
Here I am taking current date and adding 90 days to it and storing it in tocompdate
. And comparing tocompdate
with a file, where same date is present in a line and some other matter in other line before that line.
while search pattern is matched I need some text to be printed and "the line before matched line" to be printed and again matched line after few words.
For example:
File has below content
a1
28112019
b2
04032018
c3
04032018
d4
27072015
e5
27072015
f6
06012030
If I am comparing with 27072015
, I want output as below
The d4 is on 27072015
The e5 is on 27072015
Upvotes: 2
Views: 37
Reputation:
I propose a solution using only shell programming:
#!/bin/sh
match="27072015"
while IFS= read -r i
do if [ "$i" = "$match" ]
then printf "The %s is on %s\n" "$last" "$match"
fi
# test that we are not in a whitespace
if [ -n "$i" ]
then last="$i"
fi
done < tocompare.txt
Note: This solution is only appropriate for very small and simple data sets without special characters. Additionally it's much slower than using awk
.
Upvotes: 0
Reputation: 8164
Just for fun: Another solution using sed
, grep
and xargs
xargs -n 2 <file | grep -E '\b27072015$' | sed -r 's/^(\S+)\s(\S+)$/The \1 is on \2/g'
you get,
The d4 is on 27072015 The e5 is on 27072015
Upvotes: 0
Reputation: 203284
$ awk -v tgt="27072015" '$0==tgt{printf "The %s is on %s\n", p, $0} {p=$0}' file
The d4 is on 27072015
The e5 is on 27072015
Upvotes: 3