help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] how to translate one file


From: Greg Wooledge
Subject: Re: [Help-bash] how to translate one file
Date: Tue, 3 Jan 2012 08:17:38 -0500
User-agent: Mutt/1.4.2.3i

On Mon, Jan 02, 2012 at 11:46:08PM +0800, lina wrote:
> I have one file like
> 
> a 1
> b 2
> c 3
> 
> and the last line of the file like :
> 
> abc
> 
> I wish to translate it to
> 1 2 3

In bash 4, you can do this elegantly using an associative array:

#!/usr/bin/env bash
declare -A dict
while read key value; do
    # If there is no second field, then we've just read the final line.
    [[ $value ]] || break
    # Otherwise, enter this pair into our dictionary.
    dict["$key"]=$value
done

# Last line has already been read, and is in "key"
n=${#key}
for ((i=0; i<n; i++)); do
    printf "%s " "${dict["${key:i:1}"]}"
done
echo



reply via email to

[Prev in Thread] Current Thread [Next in Thread]