如何按字母顺序排列文本文件中的多行记录?

如何按字母顺序排列文本文件中的多行记录?

你好,我正在使用 bash 脚本,下面有 example.txt。我如何按餐厅名称的字母顺序排列以下 4 条有关餐厅的信息并将其打印出来?请注意,按字母顺序打印时格式应与下面的格式相同,包括城市、州、地址、电话。

Restaurant: McDonalds 
City: Miami
State: Florida
Address: 123 Biscayne Blvd
Phone: 91341

Restaurant: Five guys
City: Atlanta
State: Georgia
Address: 123 Peachtree Rd
Phone: 9234211

Restaurant: KFC
City: NYC
State: NY
Address: 123 Madison Square
Phone: 95311

Restaurant: Taco Bell
City: LA
State: CA
Address: 123 Rodeo Drive
Phone: 911

答案1

这是一个使用的解决方案awk

$ awk 'BEGIN{FS="\n";RS=""} {r[$1]=$0} END{n = asort(r); for (i=1;i<=n;i++){print r[i] "\n"}}' restaurants 
Restaurant: Five guys
City: Atlanta
State: Georgia
Address: 123 Peachtree Rd
Phone: 9234211

Restaurant: KFC
City: NYC
State: NY
Address: 123 Madison Square
Phone: 95311

Restaurant: McDonalds 
City: Miami
State: Florida
Address: 123 Biscayne Blvd
Phone: 91341

Restaurant: Taco Bell
City: LA
State: CA
Address: 123 Rodeo Drive
Phone: 911

awk每次读取文件中的一条记录。我们定义记录分隔符 ,RS以便""记录之间用空行分隔。所有记录都读入数组r。最后,对数组r进行排序并打印。

正如 @Sadi 在评论中指出的那样,该awk命令适合在管道中使用:

cat restaurants | awk 'BEGIN{FS="\n";RS=""} {r[$1]=$0} END{n = asort(r); for (i=1;i<=n;i++){print r[i] "\n"}}' >sorted_list_of_restaurants

相关内容