简体   繁体   中英

bash script read line by line and echo to file

I can't get this script to do what I want. Can someone help it's supposed to read a text file line by line and then echo the result into another file. But it's not doing recognizing the blank line. As it supposed to print the line unless it's blank then it's suppose to print to the file.

iname = checktest
while read line           
do  

if [ "$line" == "" ];
then
    echo "<blank>" >> $iname2.txt

else    
  echo "$line"  >> $iname2.txt
fi

done <$iname.txt

You cannot have spaces between variable assignment in bash.

#!/bin/bash

iname=checktest  #Should be no space between = sign
while read line; do  
    if [ -z "$line" ]; then
        echo "I saw an empty line ... will report this"
    else    
        echo "$line"  
    fi
done <"$iname".txt > newfile.txt

Also, use > after the end of loop. This prevents unnecessary I/O to open the file for writing during each loop cycle.

make some edits like this :

iname = checktest

 while read line
 do 
if [ -z "$line" ]
 then echo "" >> ${iname}2.txt
  else
 echo "$line" >> ${iname}2.txt
 fi
done  < ${iname} ;

it should work now , hope this helps ...

iname = checktest
while read line           
do  

if [ "$line" != "" ];
then
    echo $line >> 
fi

done < $iname > ${iname}2.txt

It seems more logic to me to do something when it match only.

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