Sharang
Sharang

Reputation: 11

How to extract content from a text file using sed command when line ranges are given?

#!/bin/bash

export ORACLE_SID=orcl
export ORACLE_BASE=/u01/app/oracle
export LOG_DIR=$ORACLE_BASE/diag/rdbms/$ORACLE_SID/$ORACLE_SID/trace

LINE_COUNT_OLD=0

while true
do  
    LINE_COUNT=`wc -l $LOG_DIR/alert_orcl.log | awk '{print $1}'`
    DIFF=`expr $LINE_COUNT - $LINE_COUNT_OLD`
    if [ $DIFF -ne 0 ] && [ $LINE_COUNT_OLD -ne 0 ]
    then
        COUNT=0
        COUNT=`tail -$DIFF $LOG_DIR/alert_orcl.log|grep 'ORA-'|wc -l`
        if [ $COUNT -ne 0 ]
        then
            sed -n '$LINE_COUNT_OLD, $LINE_COUNT' $LOG_DIR/alert_orcl.log > $LOG_DIR/alert_orcl_tmp.log
            cat $LOG_DIR/alert_orcl_tmp.log >> $LOG_DIR/alert_orcl_email.log
        fi
    fi
    sleep 10
    LINE_COUNT_OLD=$LINE_COUNT
    rm -f $LOG_DIR/alert_orcl_tmp.log 
done

In the above bash script getting below error

sed: -e expression #1, char 3: extra characters after command

So I have poblem with sed -n command. But replacing vairables with numbers like below line, this command is working fine

sed -n '6512, 6671 p' $LOG_DIR/alert_orcl.log

Need help to pass the variable in sed -n command

Upvotes: 1

Views: 66

Answers (2)

Ramesh
Ramesh

Reputation: 11

Use double-quoted string to pass the required parameters, so it can be evaluated by shell.

sed -n "$varA, $varB" $LOG_DIR/alert_orcl.log

Upvotes: 1

David C. Rankin
David C. Rankin

Reputation: 84531

Your primary problem with your sed command occurs because you have single-quoted the variables in:

sed -n '$LINE_COUNT_OLD, $LINE_COUNT' ...

When you single-quote variables, you prevent variable expansion by the shell, so sed literally sees:

sed -n '$LINE_COUNT_OLD, $LINE_COUNT' ...

where it attempts to resolve the literal range $LINE_COUNT_OLD, $LINE_COUNT from the characters '$' 'L' 'I' 'N' 'E' '_' 'C' 'O' 'U' 'N' 'T' '_' 'O' 'L' 'D', ...

To correct the problem, double quote you variables:

sed -n "$LINE_COUNT_OLD, $LINE_COUNT" ...

Next you have a number of little things you should update. First, avoid the use of expr $LINE_COUNT - $LINE_COUNT_OLD that is an antiquated (and slow) way of doing arithmetic. Instead use the arithmetic operators $((LINE_COUNT - LINE_COUNT_OLD)) (note: $ dereference of the variables within $((..)) is not required)

Next, unless you know the exact reason not to quote, you should double-quote all variables in bash to prevent word-splitting. Especially within [...]. Otherwhise if there is any whitespace in your variable, you will be passing an incorrect number of arguments to test. Likewise, it is also a good idea to quote the non-variables with [...] such as -ne '0' (single-quotes are fine here).

Lastly, avoid the use of ALLCAPS variable names. Those are typically reserved for use by the shell.

Upvotes: 2

Related Questions