textFileA 包括:
mango:oval:yellow:18pcs
apple:irregular:red:12pcs
orange:round:orange:4pcs
我想做一些類似允許用戶輸入的事情,例如用戶搜索“芒果”我希望系統列印出來
請輸入水果名稱:芒果>>這是用戶輸入
愿望輸出
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
uj5u.com熱心網友回復:
你可以這樣使用它:
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
uj5u.com熱心網友回復:
如果您希望通過在其中插入某些值來格式化字串,您可能會發現有用的printfStatement,請考慮以下示例,讓file.txtcontent 為
mango:oval:yellow:18pcs
apple:irregular:red:12pcs
orange:round:orange:4pcs
然后
awk 'BEGIN{FS=":"}/mango/{printf "Shape %s\nColor %s\nQuantity %s\n",$2,$3,$4}' file.txt
輸出
Shape oval
Color yellow
Quantity 18pcs
說明:我通知 GNUAWK欄位分隔符是(如果您想了解更多資訊,:請閱讀8 個強大的 Awk 內置變數 - FS、OFS、RS、ORS、NR、NF、FILENAME、FNRmango )然后對于包含Iprintf字串的行,%s被替換列的值:2nd ( $2) 3rd ( $3) 4th ( $4),\n表示換行符,所以這個 printf 確實輸出多行字串。注意尾隨換行符,因為默認情況下printf不包括在末尾。
(在 gawk 4.2.1 中測驗)
uj5u.com熱心網友回復:
使用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
uj5u.com熱心網友回復:
這是一個純粹的 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/449845.html
