textFileA consta de:
mango:oval:yellow:18pcs apple:irregular:red:12pcs orange:round:orange:4pcsQuería hacer algo como permitir la entrada del usuario, por ejemplo, la búsqueda del usuario "mango". Quiero que el sistema imprima
Ingrese el nombre de la fruta: mango >> esta es una entrada del usuario
Salida de deseo
Fruit Shape : Oval Fruit Color : Yellow Fruit Quantity : 18pcsHasta ahora, esto es lo que hice y solo podía imprimir toda la línea de cadenas, ¿hice algo mal aquí?
echo -n "Please enter the fruit name :" read fruitName awk '/'$fruitName'/ {print}' textFileASalida de corriente
mango:oval:yellow:18pcsPuedes usarlo así:
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 }' fileProducción:
Please enter the fruit name: mango Fruit Shape : oval Fruit Color : yellow Fruit Quantity : 18pcsSi desea formatear una cadena insertando ciertos valores dentro de ella, puede encontrar útil printf Statement , considere el siguiente ejemplo, deje que el contenido de file.txt sea
mango:oval:yellow:18pcs apple:irregular:red:12pcs orange:round:orange:4pcsentonces
awk 'BEGIN{FS=":"}/mango/{printf "Shape %s\nColor %s\nQuantity %s\n",$2,$3,$4}' file.txtproducción
Shape oval Color yellow Quantity 18pcs Explicación: Le informo a GNU AWK que el separador de campo es : (lea 8 potentes variables integradas de Awk: FS, OFS, RS, ORS, NR, NF, NOMBRE DE ARCHIVO, FNR si desea obtener más información) luego, para la línea que contiene mango , printf cadena, %s se reemplazan con valores de columnas: 2nd ( $2 ) 3rd ( $3 ) 4th ( $4 ), \n denota una nueva línea, por lo que este printf genera una cadena multilínea. Tenga en cuenta la nueva línea final, ya que, de forma predeterminada, printf no la incluye al final.
(probado en gawk 4.2.1)
Usando 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