Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I preserve leading whitespaces with echo on a shell script?

I have a source file that is a combination of multiple files that have been merged together. My script is supposed to separate them into the original individual files.

Whenever I encounter a line that starts with "FILENM", that means that it's the start of the next file.

All of the detail lines in the files are fixed width; so, I'm currently encountering a problem where a line that starts with leading whitespaces is truncated when it's not supposed to be truncated.

How do I enhance this script to retain the leading whitespaces?

while read line         
do         
    lineType=`echo $line | cut -c1-6`
    if [ "$lineType" == "FILENM" ]; then
       fileName=`echo $line | cut -c7-`
    else
       echo "$line" >> $filePath/$fileName
    fi   
done <$filePath/sourcefile
like image 555
heisenbergman Avatar asked Aug 05 '13 09:08

heisenbergman


2 Answers

The leading spaces are removed because read splits the input into words. To counter this, set the IFS variable to empty string. Like this:

OLD_IFS="$IFS"
IFS=
while read line         
do
    ...
done <$filePath/sourcefile
IFS="$OLD_IFS"
like image 103
petersohn Avatar answered Oct 23 '22 13:10

petersohn


To preserve IFS variable you could write while in the following way:

while IFS= read line
do
    . . .
done < file

Also to preserve backslashes use read -r option.

like image 24
rook Avatar answered Oct 23 '22 14:10

rook