Skip to content
Advertisement

How to read a file line by line

I try to read a file line by line.

File to read:

polkit|0.105
NetworkManager|0.9.4.0
GConf|3.2.5
libgnome-keyring|3.4.1
mozilla-nss|3.13.5
network-manager-applet|0.9.4.1
...

Script:

COUNTER=1
until [ $COUNTER == '$(sed $= -n /tmp/packages-install)' ]; do
    FIRST[$COUNTER]=$(head -n $COUNTER /tmp/packages-install | cut -d| -f 1)
    version[$COUNTER]=$(head -n $COUNTER /tmp/packages-install | cut -d| -f 2)
    echo "${FIRST[$COUNTER]}"
    let COUNTER=COUNTER+1
done

echo "${FIRST[2]}"

MYARRAY=()

for ((i=1; i < ${#FIRST[@]} ; i++)); do
    MYARRAY=( ${MYARRAY[@]} ${FIRST[$i]} ${version[$i]} )
done

Xdialog --menubox Choose 20 100 1 "${MYARRAY[@]}"

When I execute the script, this window will be opened: (Notice how some values are repeated, and the contents don’t correctly alternate between names and versions): Xdialog window

I’d like to create an array with all package names and versions.

Advertisement

Answer

You don’t need a counter for this at all, and invoking head twice for every single line is insanely inefficient.

array=( )
while IFS='|' read -r name version; do
  echo "Package $name is at version $version" >&2
  array+=( "$name" "$version" )
done </tmp/packages-install

See BashFAQ #001: How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement