리눅스에서 배열에 값을 저장하는 방법

리눅스에서 배열에 값을 저장하는 방법

배열에 값을 저장할 수 없습니다. 다음은 파일 데이터입니다.

123|23.23|2.34|3.45|2019-20-1

배열의 두 번째, 세 번째, 네 번째 값을 원합니다. 나중에 3개 매개변수나 다른 필드 조합 대신 4개 매개변수를 선택할 수 있도록 코드는 일반적이어야 합니다.

array ={23.33 2.34 3.45 2019-20-1}

작업 코드의 일부:

declare -a alpha=()

alpha=($(awk '{n = split($0, t, "|")
for(i = 0; ++i <= n;) print t[i]}' <<<'$2|$3|$4'))
echo "$alpha[@]"

입력을 다음과 같이 전달합니다.'$2|$3|$4'

아래와 같은 배열 출력을 원합니다.

alpha={$2 $3 $4}

인쇄할 때 echo "${alpha[@]}"모든 값이 인쇄되어야 합니다.

산출: $2 $3 $4

*참고: 이 값을 추가 코드의 루프로 사용하여 다른 값을 얻을 수 있도록 출력에는 두 값 사이에 공백이 있어야 합니다.

답변1

bash read명령은 필드를 배열에 저장할 수 있습니다.

while IFS='|' read -r -a fields; do
    # do stuff with the elements of "${fields[@]}"
done < file

답변2

이것은 귀하의 경우에 작동합니다

alpha=( $(awk -F'|'  '{ for(i=1;++i<=NF;) printf $i" "}' yourfile ) )

NF(하드코드된 필드 번호 대신 필드 번호)를 사용합니다.

답변3

#!/bin/bash

# Read the data into the array fields from the
# file called "file". This assumes that the data
# is a single line with fields delimited by
# |-characters.
mapfile -d '|' -t fields <file

# The last entry in the fields array will quite
# likely have a trailing newline at the end of it.
# Remove that newline if it exists.
fields[-1]=${fields[-1]%$'\n'}

# These are the column numbers from the original
# data that we'd like to keep.
set -- 2 3 4

# Extract those columns from the fields array. Note
# that we have to decrement the numbers by one as
# arrays in bash are indexed from zero.
for column do
        array+=( "${fields[column-1]}" )
done

# Output the elements of the resulting array:
printf '%s\n' "${array[@]}"

# For outputting with spaces in-between the values
# rather than newlines:
printf '%s\n' "${array[*]}"

이유없이산출다른 용도로 사용하고 싶다면 배열의 값을 마지막에 추가하세요. 특정 형식으로 값을 출력하고 싶다고 가정해 보겠습니다.(그 사이에 공백이 있습니다)당신이 그것들을 파싱해야한다는 것을 의미합니다다시그리고 다른 코드. 그건 전혀 불필요해요 왜냐면 당신은이미배열에 값이 있습니다.

값 배열을 반복합니다.

for value in "${array[@]}"; do
    # Use "$value" here.
done

또는 원시 데이터 배열을 사용하십시오 fields.

for column in 2 3 4; do
    value=${fields[column-1]}
    # Use "$value" here.
done

답변4

bash매개변수 확장이나 명령 대체 또는 산술 확장을 인용하지 않으면 $(<...)분할이 발생합니다 .

그래서 여기 있습니다:

IFS='|'                # split on | instead of the default of SPC|TAB|NL

set -o noglob          # disable globbing which is another side effect of leaving
                       # expansions unquoted

set -- $(<file.data)'' # do the splitting. The extra '' is so that
                       # a|b| is split into "a", "b" and "" for instance.
                       # also note that it splits an empty string into one empty
                       # element.

array=("$2" "$3" "$4")

관련 정보