I am trying this simple while
loop in bash.
My text file
# cat test.txt
line1:21
line2:25
line5:27
These are all on new line
My Script
# cat test1.sh
while read line
do
awk -F":" '{print 2ドル}'
done < test.txt
Output
# ./test1.sh
25
27
The output isn't printing the first line 2ドル
value. Could anyone please help me understand this case?
-
See also Why is using a shell loop to process text considered bad practice?Stéphane Chazelas– Stéphane Chazelas2017年05月20日 21:56:37 +00:00Commented May 20, 2017 at 21:56
3 Answers 3
You don't need that loop:
$ awk -F ':' '{ print 2ドル }' test.txt
21
25
27
awk
will process the input line by line.
With your loop, the read
will get the first line of the file, which is lost since it's not used/outputted. The awk
will then take over the standard input of the loop and read the other two lines in the file (so the loop will only ever do one single iteration).
Your loop, annotated:
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
I able to fix your code by adding echo
. Reason for this have described there, question why it's printing other two values.
while read line;
do
echo "$line" | awk -F":" '{print 2ドル}'
done < test.txt
while IFS=":" read z x; do
echo $x;
done<test.txt
or
sed "s/^.*://g" test.txt