
Estoy probando este while
bucle simple en bash.
mi archivo de texto
# cat test.txt
line1:21
line2:25
line5:27
These are all on new line
Mi guión
# cat test1.sh
while read line
do
awk -F":" '{print $2}'
done < test.txt
Producción
# ./test1.sh
25
27
El resultado no imprime el $2
valor de la primera línea. ¿Alguien podría ayudarme a entender este caso?
Respuesta1
No necesitas ese bucle:
$ awk -F ':' '{ print $2 }' test.txt
21
25
27
awk
procesará la entrada línea por línea.
Con su bucle, read
obtendrá la primera línea del archivo, que se pierde porque no se usa ni se genera. Luego awk
tomará la entrada estándar del bucle y leerá las otras dos líneas del archivo (por lo que el bucle solo realizará una única iteración).
Tu bucle, anotado:
while read line # first line read ($line never used)
do
awk -F ':' '{ print $2 }' # reads from standard input, which will
# contain the rest of the test.txt file
done <test.txt
Respuesta2
Puedo arreglar tu código agregando echo
. La razón de esto ha sido descrita.allá, pregunte por qué está imprimiendo otros dos valores.
while read line;
do
echo "$line" | awk -F":" '{print $2}'
done < test.txt
Respuesta3
while IFS=":" read z x; do
echo $x;
done<test.txt
o
sed "s/^.*://g" test.txt