繁体   English   中英

我如何将while读取行循环的内容输出到bash中的多个数组?

[英]how do I output the contents of a while read line loop to multiple arrays in bash?

我读取目录中的文件并将每个文件名放入一个数组(SEARCH),然后使用循环遍历该数组中的每个文件名(SEARCH),并使用while read line loop打开它们并将其读入另一个数组(文件计数)。 我的问题是它的一个巨大的数组有39行(每个文件有13行),我需要它是3个单独的数组,其中filecount1 [line1]是第一个文件的第一行,依此类推。 到目前为止,这是我的代码...

typeset -A files
for file in ${SEARCH[@]}; do
    while read line; do
        files["$file"]+="$line"
    done < "$file"
done

所以,谢谢伊凡的这个例子! 但是我不确定我如何将其放入一个单独的数组中,因为在此示例中,所有数组都仍将命名为“文件”吗?

如果您只是试图将文件内容存储到数组中:

declare -A contents
for file in "${!SEARCH[@]}"; do
    contents["$file"]=$(< $file)
done

如果要将单个行存储在数组中,则可以创建一个伪多维数组:

declare -A contents
for file in "${!SEARCH[@]}"; do
    NR=1
    while read -r line; do
        contents["$file,$NR"]=$line
        (( NR++ ))
    done < "$file"
done

for key in "${!contents[@]}"; do 
    printf "%s\t%s\n" "$key" "${contents["$key"]}"
done

第6行是

$filecount[$linenum]}="$line" 

似乎在$之后紧接{
应该:

${filecount[$linenum]}="$line" 

如果上述属实,那么试图运行输出为命令
第6行是(在“固定”上面之后):

${filecount[$linenum]}="$line"

但是${filecount[$linenum]}是一个 ,您不能在value上赋值
应该:

filecount[$linenum]="$line"

现在我很困惑,例如{是否实际上丢失了,或者}是实际的错别字:S:P


btw,bash也支持此语法

filecount=$((filecount++)) # no need for $ inside ((..)) and use of increment operator ++

这应该工作:

typeset -A files
for file in ${SEARCH[@]}; do       # foreach file 
    while read line; do            # read each line
        files["$file"]+="$line"    # and place it in a new array
    done < "$file"                 # reading each line from the current file
done

一次小测试表明它有效

# set up
mkdir -p /tmp/test && cd $_
echo "abc" > a
echo "foo" > b
echo "bar" > c

# read files into arrays
typeset -A files
for file in *; do 
    while read line; do
        files["$file"]+="$line" 
    done < "$file"
done

# print arrays
for file in *; do
    echo ${files["$file"]}
done

# same as:
echo ${files[a]}     # prints: abc
echo ${files[b]}     # prints: foo
echo ${files[c]}     # prints: bar

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM