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



textFileA包括:

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

我想做一些事情,比如允许用户输入,例如用户搜索";芒果";我想让系统打印出

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

所需输出

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" '
$1 == fruitName {
print "Fruit Shape :", $2
print "Fruit Color :", $3
print "Fruit Quantity :", $4
}' file

输出:

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

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

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

然后

awk 'BEGIN{FS=":"}/mango/{printf "Shape %snColor %snQuantity %sn",$2,$3,$4}' file.txt

输出

Shape oval
Color yellow
Quantity 18pcs

解释:我通知GNUAWK,字段分隔符是:(如果你想了解更多,请阅读8个强大的Awk内置变量–FS、OFS、RS、ORS、NR、NF、FILENAME、FNR(,然后对于包含mangoprintf字符串的行,%s被列的值替换:第二($2(第三($3(第四($4(,n表示换行,所以这个printf确实输出多行字符串。注意后面的换行符,因为默认情况下printf在末尾不包括它。

(在gawk 4.2.1中测试(

使用awk

$ awk -F: 'BEGIN {printf "Please enter fruit name: "; getline fruit < "-"} $1==fruit {print "Fruit Shape: " $2 "nFruit Color: " $3 "nFruit Quantity: " $4}' 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 < "-"
} $1==fruit {
print "Fruit Shape: " $2 "nFruit Color: " $3 "nFruit Quantity: " $4
}
$ awk -F: -f file.awk input_file
Please enter fruit name: mango
Fruit Shape: oval
Fruit Color: yellow
Fruit Quantity: 18pcs

这里有一种纯粹的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  

相关内容

  • 没有找到相关文章

最新更新