0

2つのファイルがあります。1つには動物の名前が含まれています:

martin@potato:~$ cat animals.txt 
98 white elefant
103 brown dog
111 yellow cat
138 blue whale
987 pink pig
martin@potato:~$

..およびその他には、彼らが住んでいる場所が含まれています:

martin@potato:~$ cat places.txt 
98 safari
99
103 home
105
109
111 flat
138 ocean
500
987 farm
989
martin@potato:~$ 

animal.txtの動物名の前の数字は、正しい場所を指しています。出力は次のようになります。

martin@potato:~$ ./animals.sh
safari  white elefant
home    brown dog
flat    yellow cat
ocean   blue whale
farm    pink pig
martin@potato:~$ 

動物の名前と場所をマッピングするためのbashで最もエレガントなソリューションは何ですか?

私はこのようにしました:

#!/usr/bin/env bash

#content of animals.txt file is stored into "$animals" variable using command substitution
animals=$(<animals.txt)

#content of places.txt file is stored into "$places" variable using command substitution
places=$(<places.txt)


#read(bash builtin) reads "$animals" variable line by line
while read line; do

    #"$animals_number" variable contains number in the beginning of the line; for example "98" in case of first line
    animals_number=$(echo "$line" | sed 's/ .*$//')
    #"$animals_name" variable contains string after number; for example "white elefant" in case of first line
    animals_name=$(echo "$line" | sed 's/[0-9]* //')
    #"$animals_place" variable contains the string after line which starts with "$animals_number" integer in places.txt file;
    #for example "safari" in case of first line
    animals_place=$(echo "$places" | grep -Ew "^$animals_number" | sed 's/.* //')
    #printf is used to map two strings which share the same integer in the beginning of the line
    printf '%s\t%s\n' "$animals_place" "$animals_name"

#process substitution is used to redirect content of "$animals" variable into sdtin of while loop
done < <(echo "$animals")

ただし、これがこの問題を解決するための最もエレガントで効率的な方法かどうかはわかりません。追加の方法/テクニックはありますか?

4

2 に答える 2

3
while read id place;  do places[$id]=$place;                           done < places.txt
while read id animal; do printf '%s\t%s\n' "${places[$id]}" "$animal"; done < animals.txt
于 2012-11-22T18:46:06.320 に答える
0
join <(sort animals.txt) <(sort places.txt) | sort -n

残念ながら、join「数値的にソートされた」オプション、afaikはありません。それ以外の場合はjoin、すべてを2回ソートする代わりに、2つのファイルだけを並べ替えることができます。(ファイルに先行ゼロを入れると、sortsがなくても機能します。)

最近のubuntus、およびおそらく他のLinuxディストリビューションは、LANG推定されるロケールに設定されています。これは、 ;sortとは異なり、ロケールを認識するために致命的です。join上記が機能するためには、ソート順について合意する必要がありますjoinsort次のようなエラーが発生した場合:

join: /dev/fd/63:5: is not sorted: 98 white elefant

次に、これを試してください:

( export LC_ALL=C;  join <(sort animals.txt) <(sort places.txt) | sort -n )
于 2012-11-22T23:34:36.310 に答える