【问题标题】:Translate Perl code to shell将 Perl 代码转换为 shell
【发布时间】:2018-08-23 08:30:45
【问题描述】:

我有一个子程序需要读取文件并将数据存储在 Perl 中的哈希中

while ( $input = <file> ) { # Reading Line by line

    for my $term ( split /[=]/, $input ) {
        my ($value, $newkey) = ($term =~ /(.*?) (\S+)$/);
        $record{$key} = $value;
        $key = $newkey; 
    }

我需要在 shell 中编写相同的内容。到目前为止,我可以拆分数据,但不能从哈希中放入或检索。

【问题讨论】:

  • 您将帖子标记为“shell”,因此我得出结论,您的意思是 Posix shell。 posix shell 中没有关联数组。实际上,posix shell 中根本没有数组(除了保存参数的@-array)。
  • 请指定哪个shell
  • SO 不是代码编写服务,所以不要要求翻译。相反,请询问如何做您遇到困难的事情。

标签: shell


【解决方案1】:

这是一个在 Bash shell 中使用关联数组(即哈希)的示例:

#! /bin/bash

declare -A record  # Declare an associative array
file=file.txt
key="key0"
while read -r line; do  # Read file line by line
    read -r -a fields <<< "$line" # Split line by white space into fields array
    value="${fields[-2]}" # extract next to last field on line
    newkey="${fields[-1]}" # extract last field
    record[$key]="$value"  # insert into associative array
    key="$newkey"
done < "$file"

for key in "${!record[@]}" ; do
    echo "$key =  ${record[$key]}"
done

【讨论】:

  • 我怎样才能做到相同的 id 数据在文件中的单行上被“=”符号分割
  • 一行中的数据格式为 data1=val1 data2=val2 ....datan=valn 按上述逻辑我只能对最后一个和倒数第二个字段执行此操作,我需要为行中的所有字段
  • 尝试使用 IFS 变量在分隔符上拆分,有关更多信息,请参阅 How do I split a string on a delimiter in Bash?
猜你喜欢
  • 2020-01-18
  • 2017-05-06
  • 2011-03-14
  • 1970-01-01
  • 2019-11-27
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 2010-09-28
相关资源
最近更新 更多