简体   繁体   English

bash脚本无法读取第一行

[英]bash script fails to read first line

I have a script to convert timestamps into seconds so I can eventually work out the averages. 我有一个脚本将时间戳转换为秒,所以我最终可以计算平均值。 I noticed that the number of output lines did not equal the amount of input lines. 我注意到输出行的数量不等于输入行的数量。 In fact it does not seem to read the first line. 实际上它似乎没有阅读第一行。 I simplified the code to check it but it is the same every time. 我简化了代码来检查它,但每次都是一样的。

Input file looks like this: 输入文件如下所示:

00:00:01
00:00:02
00:00:03

Output like this: 输出如下:

00 00 02
00 00 03

This is the script: 这是脚本:

#!/bin/bash

while read line
do
    awk -F: '{ print $1, $2, $3 }' > /home/time.log

done < /home/timestamp.log

I'm sure it is something stupid but I cannot see it! 我确定这是愚蠢的,但我看不到它!

You don't need a loop. 你不需要循环。 You can simply use awk: 你可以简单地使用awk:

awk -F: '{ print $1, $2, $3 }' /home/timestamp.log > /home/time.log

The reason for the behaviour you see is that you don't pass the line to awk. 您看到的行为的原因是您没有将该line传递给awk。 So the first line is read by read the loop and rest by awk inside the loop as awk gets it stdin from the loop. 所以读取循环读取第一行,并在循环中通过awk休息,因为awk从循环中获取stdin Hence, you don't see the first line. 因此,你没有看到第一行。

If it's still not clear, just add a echo "Hello" after the awk call inside your loop and see how many times it gets printed :) 如果它仍然不清楚,只需在循环中的awk调用添加一个echo "Hello" ,看看它被打印多少次:)

You probably intended to do: 你可能打算这样做:

echo $line | awk -F: '{ print $1, $2, $3 }' > /home/time.log

But that's just unnecessary. 但这只是不必要的。

read line is consuming the first line of the input, and assigning it to the Bash variable $line , which you then ignore. read line消耗输入的第一行,并将其分配给Bash变量$line ,然后忽略该$line Then the body of the loop is processing the rest of the file using awk. 然后循环体正在使用awk处理文件的其余部分。

You can just use awk directly without the loop: 你可以直接使用awk而不需要循环:

awk -F: '{ print $1, $2, $3 }' /home/timestamp.log > /home/time.log

Or you can use a loop and not awk: 或者您可以使用循环而不是awk:

while IFS=: read h m s; do echo $h $m $s >> /home/time.log; done < /home/timestamp.log

You can also use tr to your advantage here: 你也可以在这里使用tr

tr ':' ' ' < /home/timestamp.log

It will provide the translation of characters you need. 它将提供您需要的字符翻译。 Eg: 例如:

$ tr ':' ' ' <dat/timestamp.log
00 00 01
00 00 02
00 00 03

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM