English 中文(简体)
从文件进行队列
原标题:Array from a file
  • 时间:2012-05-25 17:17:13
  •  标签:
  • bash

如果我有这样的文件:

A:a
B:b
C:c

我需要创造两个阵列

one=( A   B   C )
two=( a   b   c )

我怎样才能在狂欢中做呢?

我试过了

declare -a one
declare -a two

while read line
do
    IFS= :  read -ra ADDR <<< $line
    echo ${ADDR[0]}
    echo ${ADDR[1]}
done < file.txt

抱歉我写了件工作,然后回家。 再次抱歉。 问题在于它正在打印

littlelion:Documents dierre$ sh prova.sh 
A a

B b

所以它丢失了 C c 和我不知道如何在数组中添加元素

最佳回答

引数修正一切 :

while read line
do
    IFS= :  read -ra ADDR <<< "$line"
    echo ${ADDR[0]}
    echo ${ADDR[1]}
done < file.txt

引用变量 < code> "$line" 是区别所在。 如果您没有用“ C: c” 获得线条, 很可能是因为您的文件缺少最终的新行 。

问题回答

如果我理解你正试图做正确的事情,这应该行得通:

one=()
two=()
while IFS=: read new_one new_two || [ -n "$new_one" ]; do
    one+=("$new_one")
    two+=("$new_two")
done
echo "one:" "${one[@]}"
echo "two:" "${two[@]}"

注意:我同意@Dennis Williamson的观点, 最后一行没有被处理, 因为它没有以新线结束; 我添加了 < code\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

使用 < a href=>" "http://tldp.org/LDP/abs/html/commandasub.html" rel="nofollow" >command compresidation :

declare -a one
declare -a two

one=( $(cut -d: -f1 file) )
two=( $(cut -d: -f2 file) )

var=$( command) 捕捉到您命令的输出, 并将其指定为 var 。 外部占卜者将此项指派为数组 。 cut- d: - f1 表示要将您的文件作为结肠分隔的文件处理, 并打印第一个字段 。 cut - d: -f2 也这样做, 但是它打印了第二个字段 。


编辑响应 OP s 编辑

您可直接读入 ADDD 如下:

declare -a ADDR
while IFS= :  read -a ADDR; do
  echo ${ADDR[0]}
  echo ${ADDR[1]}
done < file.txt

虽然不会弹出数组 one two ...





相关问题
Parse players currently in lobby

I m attempting to write a bash script to parse out the following log file and give me a list of CURRENT players in the room (so ignoring players that left, but including players that may have rejoined)...

encoding of file shell script

How can I check the file encoding in a shell script? I need to know if a file is encoded in utf-8 or iso-8859-1. Thanks

Bash usage of vi or emacs

From a programming standpoint, when you set the bash shell to use vi or emacs via set -o vi or set -o emacs What is actually going on here? I ve been reading a book where it claims the bash shell ...

Dynamically building a command in bash

I am construcing a command in bash dynamically. This works fine: COMMAND="java myclass" ${COMMAND} Now I want to dynamically construct a command that redirectes the output: LOG=">> myfile.log ...

Perform OR on two hash outputs of sha1sum

I want perform sha1sum file1 and sha1sum file2 and perform bitwise OR operation with them using bash. Output should be printable i.e 53a23bc2e24d039 ... (160 bit) How can I do this? I know echo $(( ...

Set screen-title from shellscript

Is it possible to set the Screen Title using a shell script? I thought about something like sending the key commands ctrl+A shift-A Name enter I searched for about an hour on how to emulate ...