简体   繁体   中英

shell script taking last empty line of a file also

I have a script:

#! /usr/bin/ksh

TODAY=$(date +%Y%m%d)
list=$1
FILE_NAME="IMEI.txt"
OUTFILE="${list}_list.out"

##########################################
if [ -z ${list} ]
then
    echo "Use the syntax ./add_imei.sh <list number>"
    exit 0
fi

while read LINE
do
    IMEI=`echo $LINE | 
        sed 's/ //g' | sed -e 's/[^ -~]//g'`
    END_SERIAL=`echo $IMEI |
        cut -c9- | sed 's/ //g' | 
                sed -e 's/[^ -~]//g'`
    echo \
        "CRE:EQU,${IMEI}0,${END_SERIAL},${list},,${TODAY};" \
            >> ${OUTFILE}i
done < "${FILE_NAME}"

The script will take 14 digit number from every line of the file IMEI.txt , build a command like:

CRE:EQU,777777777777770,777777,0,,20130611;

and save it in a seperate output file. Pretty simple job. Everything is working fine, but when I look into the output file I see this:

CRE:EQU,444444444444440,444444,0,,20130611;
CRE:EQU,555555555555550,555555,0,,20130611;
CRE:EQU,666666666666660,666666,0,,20130611;
CRE:EQU,777777777777770,777777,0,,20130611;
CRE:EQU,0,,0,,20130611; <-- *)

*) for the last empty line of the input line also (as i hit a last enter while saving the input file) it's building a command in output file which I don't want. Any quick, short and smart way to resolve this?

while read LINE
do
    [ -z "$LINE" ] && continue
    IMEI=$(echo $LINE | sed 's/ //g' | sed -e 's/[^ -~]//g')
    END_SERIAL=$(echo $IMEI | cut -c9- | sed 's/ //g' | sed -e 's/[^ -~]//g')
    echo "CRE:EQU,${IMEI}0,${END_SERIAL},${list},,${TODAY};" >> ${OUTFILE}i
done < "${FILE_NAME}"

If the line is empty, continue with the next iteration of the loop.

Or have sed delete blank lines (containing blanks and tabs only) before feeding the file to the loop:

sed '/^[     ]*$/d' "$FILE_NAME" |
while read LINE
do
    IMEI=$(echo $LINE | sed 's/ //g' | sed -e 's/[^ -~]//g')
    END_SERIAL=$(echo $IMEI | cut -c9- | sed 's/ //g' | sed -e 's/[^ -~]//g')
    echo "CRE:EQU,${IMEI}0,${END_SERIAL},${list},,${TODAY};" >> ${OUTFILE}i
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM