Issue when doing a loop

Hi,

I just have started learning shell scripting (sh). Why do i only get the date?

while read dt
do
   echo "Date : ${dt}
   sed -n '/${dt}/,/${dt}/p' file1.log | grep -w ERROR
done < date1.dat


INPUT - date1.dat

2019-04-05 04:58:25
2019-04-05 04:58:26
2019-04-05 05:00:56
2019-04-05 05:08:26
2019-04-05 05:14:08
2019-04-05 05:21:26
2019-04-05 05:31:08

Desired Output

Date : 2019-04-05 04:58:25
2019-04-05 04:58:25,696 [Timer-7] ERROR :  421 Exceeded allowable connection time, disconnecting.

Actual Output

Date : 22019-04-05 04:58:25
Date : 22019-04-05 04:58:26
Date : 22019-04-05 05:00:56
Date : 22019-04-05 05:08:26
Date : 22019-04-05 05:14:08
Date : 22019-04-05 05:21:26
Date : 22019-04-05 05:31:08

The sed does not find anything.
Your mistake is the 'ticks' around $dt, but the shell only expands $dt within "quotes".
Further, a /x/,/x/ range is always one line, so you can simply address it with one /x/ .
Further, consider searching only at the beginning of the lines, by means of /^x/ , here /^$dt/ or /^${dt}/
Further, you can save the invocation of grep.

sed -n "/ERROR/!d; /^$dt/p" file1.log

or

sed "/ERROR/!d; /^$dt/!d" file1.log

Note: in bash you need to turn off history substitution with comand set +H .

1 Like

Thank you MadeInGermany.
Do i always need to turn off history substitution?

Only in an interactive bash shell (i.e. the command line), an exclamation mark followed by an alphanumeric character does history substitution.
For example

echo "!1"

prints line 1 from the command history .
Fortunately a bash script never does history substitution; a set +H work-around is not needed there.

1 Like