简体   繁体   中英

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窗口

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

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)?

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