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