Passing from string to array doesn't work as expected in Bash

I want to put the result of the sort method into an array in which each cell contains a word. I tried this code, but only part of the $ file is printed and not sorted:

#!/bin/bash
for file in `ls ${1}` ; do
    if [[ ! ($file = *.user) ]] ; then
        continue
    fi

    arr=(`sort -nrk4 $file`)
    echo ${arr[*]}

done

Why is this not working? How can i do this?

Data file:

name1 01/01/1994 a 0
name2 01/01/1994 b 5
name3 01/01/1994 c 2

If I run only sorting (sort -nrk4 $ file), this will print:

name2 01/01/1994 b 5
name3 01/01/1994 c 2
name1 01/01/1994 a 0

When I run 2 lines above, this is what was printed:

 name1 01/01/1994 a 0
+3
source share
1 answer

In order for each line of output to sortbe placed in its own element of the array, IFSit is necessary to install in a new line. To output an array, you need to iterate over it.

#!/bin/bash
for file in $1; do
    if [[ ! $file = *.user ]]; then
        continue
    fi

    saveIFS=$IFS
    IFS=$'\n'
    arr=($(sort -nrk4 "$file"))
    IFS=$saveIFS
    for i in "${arr[@]}"
    do
        echo "$i"
    done

done

, reset IFS, , , , IFS , * :

echo "${arr[*]}"

, .

ls for. $1 globbing, . , , . , $1 , .

, , .

$(). .

, , , . , @ .

+1

All Articles