使用 awk 从文件中检索一组特定的字符串

Using awk to retrieve a specific set of strings from a file

textFileA 包括:

mango:oval:yellow:18pcs
apple:irregular:red:12pcs
orange:round:orange:4pcs

我想做一些事情,比如允许用户输入,例如用户搜索“mango” 我要系统打印出来

请输入水果名称:芒果 >> 这是用户输入

期望输出

Fruit Shape : Oval
Fruit Color : Yellow
Fruit Quantity : 18pcs

到目前为止,这就是我所做的,它只能打印出整行字符串,我在这里做错了吗?

echo -n "Please enter the fruit name :"
read fruitName
awk '/'$fruitName'/ {print}'  textFileA

当前输出

mango:oval:yellow:18pcs

你可以这样使用它:

read -p "Please enter the fruit name: " fruitName
awk -F: -v fruitName="$fruitName" '
 == fruitName {
   print "Fruit Shape :", 
   print "Fruit Color :", 
   print "Fruit Quantity :", 
}' file

输出:

Please enter the fruit name: mango
Fruit Shape : oval
Fruit Color : yellow
Fruit Quantity : 18pcs

使用awk

$ awk -F: 'BEGIN {printf "Please enter fruit name: "; getline fruit < "-"} ==fruit {print "Fruit Shape: "  "\nFruit Color: "  "\nFruit Quantity: " }' input_file
Please enter fruit name: mango
Fruit Shape: oval
Fruit Color: yellow
Fruit Quantity: 18pcs
$ cat file.awk
BEGIN {
    printf "Please enter fruit name: "; getline fruit < "-"
} ==fruit {
    print "Fruit Shape: "  "\nFruit Color: "  "\nFruit Quantity: " 
}
$ awk -F: -f file.awk input_file
Please enter fruit name: mango
Fruit Shape: oval
Fruit Color: yellow
Fruit Quantity: 18pcs

如果您希望通过在其中插入某些值来格式化字符串,您可能会发现有用 printf Statement,请考虑以下示例,让 file.txt 内容为

mango:oval:yellow:18pcs
apple:irregular:red:12pcs
orange:round:orange:4pcs

然后

awk 'BEGIN{FS=":"}/mango/{printf "Shape %s\nColor %s\nQuantity %s\n",,,}' file.txt

产出

Shape oval
Color yellow
Quantity 18pcs

说明:我通知 GNU AWK 字段分隔符是 :(如果您想了解更多,请阅读 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR)然后对于包含 mango 的行我 printf字符串,%s替换为列的值:2nd (</code>) 3rd (<code>) 4th (</code>),<code>\n表示换行,所以这个 printf 确实输出多行字符串。请注意尾随换行符,因为默认情况下 printf 不在末尾包含它。

(在 gawk 4.2.1 中测试)

这里是一个纯粹的Bash方式:

#!/bin/bash

read -p "Please enter the fruit name: " tgt 

keys=("Fruit Shape" "Fruit Color" "Fruit Quantity") 

while IFS= read -r line; do
    arr=(${line//:/ })
    if [[ "${arr[0]}" = "$tgt" ]]; then
        for (( i=0; i<"${#keys[@]}"; i++ )); do 
            echo "${keys[$i]}: ${arr[( $i+1 )]}"
        done
        break 
    fi  
done <file