Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays Bash-将Postgresql零分隔字段读入数组_Arrays_Bash_Postgresql - Fatal编程技术网

Arrays Bash-将Postgresql零分隔字段读入数组

Arrays Bash-将Postgresql零分隔字段读入数组,arrays,bash,postgresql,Arrays,Bash,Postgresql,我想将使用--field separator zero生成的psql查询的输出读入bash脚本中的数组。我所做的最好的尝试是: psql -w -t --quiet --no-align --field-separator-zero -c $'select nickname,first_name,last_name,email from users' | while IFS= read -d '' -a USERS; do echo ${USERS[0]} ${USERS[1]}

我想将使用--field separator zero生成的psql查询的输出读入bash脚本中的数组。我所做的最好的尝试是:

psql -w  -t --quiet --no-align --field-separator-zero -c $'select nickname,first_name,last_name,email from users' | while IFS= read -d '' -a USERS; do 
     echo ${USERS[0]} ${USERS[1]} ${USERS[2]} ${USERS[3]}; 
done;

上面的命令将以新数组的形式返回行中的每个字段。将分隔符更改为其他任何字符都可以使流程正常工作,但问题是昵称字段可能包含任何字符,因此我不得不使用安全NUL char作为分隔符。有没有办法做到这一点

我在这里假设昵称是唯一的密钥;如果该角色中应使用不同的字段,请进行适当的修改

下面的代码将数据读入一系列关联数组,并依次发射每一行

请注意,关联数组是Bash4的一个特性;如果您使用的是3.2版本的Mac OS,请使用MacPorts或类似工具安装现代版本

declare -A first_names=( ) last_names=( ) emails=( )
while IFS= read -r -d '' nickname && \
      IFS= read -r -d '' first_name && \
      IFS= read -r -d '' last_name && \
      IFS= read -r -d '' email; do
  first_names[$nickname]=$first_name
  last_names[$nickname]=$last_name
  emails[$nickname]=$email
done < <(psql ...)

echo "Found users: "
for nickname in "${!emails[@]}"; do
  printf 'nickname - %q\n' "$nickname"
  printf 'email - %q\n' "${emails[$nickname]}"
  printf 'first name - %q\n' "${first_names[$nickname]}"
  printf 'last name - %q\n' "${last_names[$nickname]}"
  echo
done
declare-A名字=()姓氏=()电子邮件=()
而IFS=read-r-d“”昵称&&\
IFS=读-r-d''名&&\
IFS=读-r-d''姓&&\
IFS=读取-r-d''电子邮件;做
名字[$昵称]=$first\u name
姓氏[$昵称]=$last\u name
电子邮件[$昵称]=$email

done<真的很复杂,这与我的预期有关,但我认为没有更好的方法,因为bash的局限性在我看来并不复杂,但我认为这在很大程度上是熟悉的功能。如果您想避免某些特定的事情(例如使用关联数组),请告诉我。@Iman,…实际上,这里的核心点是
IFS=read-r-d'
。诚然,其中2/3的RD正在清除标准合规性强制要求的不幸默认值(没有
-r
read
由POSIX定义,以扩展反斜杠转义序列,而不是按字面返回数据;没有清除
IFS
,在读取字段后,会再次按照POSIX从字段中删除尾随空格)。
-d'
告诉它分隔符是NUL——这是因为shell使用C字符串;取消引用空字符串的第一个字符,将得到一个NUL。