我正在whilebash 中尝试这个简单的循环。
我的文本文件
# cat test.txt
line1:21
line2:25
line5:27
These are all on new line
Run Code Online (Sandbox Code Playgroud)
我的脚本
# cat test1.sh
while read line
do
awk -F":" '{print $2}'
done < test.txt
Run Code Online (Sandbox Code Playgroud)
输出
# ./test1.sh
25
27
Run Code Online (Sandbox Code Playgroud)
输出不打印第一行$2值。任何人都可以帮助我理解这个案例吗?
你不需要那个循环:
$ awk -F ':' '{ print $2 }' test.txt
21
25
27
Run Code Online (Sandbox Code Playgroud)
awk 将逐行处理输入。
使用您的循环,read将获得文件的第一行,由于未使用/输出,该行已丢失。在awk随后将接管循环的标准输入和读取文件中的其他两行(这样的循环将永远只能做一个单一的迭代)。
你的循环,注释:
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
Run Code Online (Sandbox Code Playgroud)