Tuesday, March 12, 2019

Reading a Text File Line by Line using Shell Script

Open a text file for reading where $1 is the command argument for the file:

#!/bin/bash
while read line; do
    echo "$line"
done < $1

If you want to skip empty lines...

#!/bin/bash
while read line; do
if [ ! -z "$line" ]; then
echo "$line"
fi
done < $1

if you want to skip lines starting with '#'...

#!/bin/bash
while read line; do
if [ ! -z "$line" ]; then
if [[ ! "$line" == \#* ]]; then
echo "$line"
fi
done < $1

if line has <field> <value> pair separated by ':' e.g. name:john, do this:

while read line; do
if [ ! -z "$line" ]; then
if [[ ! "$line" == \#* ]]; then
left=${line%:*}
echo "$left"
right=${line#*:}
echo "$right"
fi
fi 
done < $1

where 'left' is <field> and 'right' is <value>



No comments:

Post a Comment