-4

I have a subroutine needed to read file and store data in a hash in Perl

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

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

I need to write same in shell. So far I can split the data, but can't put or retrieve from a hash.

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • You are tagging your post "shell", so I conclude that you mean Posix shell. There are no associative arrays in posix shell. Actually, there are no arrays in posix shell at all (with the exception of the @-array which holds the parameters). – user1934428 Aug 23 '18 at 09:01
  • Please specify which shell – ikegami Aug 23 '18 at 19:36
  • SO is not a code-writing service, so don't ask to translate. Instead, ask how to do what you are having trouble doing. – ikegami Aug 23 '18 at 19:36

1 Answers1

0

Here is an example using an associative array (i.e. hash) in the 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
Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174
  • how can i do the same id the data is split by an "=" sign on a single line in file – vicky joshi Aug 23 '18 at 11:41
  • the data in one line is in format is data1=val1 data2=val2 ....datan=valn by above logic i can do only for last and second last field , i need to do it for all fields in line – vicky joshi Aug 23 '18 at 11:57
  • Try split on a delimiter using the `IFS` variable, see [How do I split a string on a delimiter in Bash?](https://stackoverflow.com/q/918886/2173773) for more information – Håkon Hægland Aug 23 '18 at 14:02