阅读使用awk串行输入,插入日期 [英] Read serial input with awk, insert date
问题描述
我试图重新格式化串行输入,它由一个逗号(从一个Arduino发送)分开的两个整数的:
I'm trying to reformat serial input, which consists of two integers separated by a comma (sent from an Arduino):
1,2
3,4
0,0
0,1
等。我想在每行后的日期追加,用制表符分隔的一切。这里是我的code迄今:
etc. I would like to append the date after each line, separating everything with a tab character. Here's my code so far:
cat /dev/cu.usbmodem3d11 | awk 'BEGIN {RS=","};{printf "%i\t%i\t%s",$1,$2,system("date")}'
下面是结果我得到(与日期在我的区域):
Here's the result I get (with date in my locale):
1 2 0Mer 26 fév 2014 22:09:20 EST
3 4 0Mer 26 fév 2014 22:09:20 EST
0 0 0Mer 26 fév 2014 22:09:20 EST
0 1 0Mer 26 fév 2014 22:09:20 EST
为什么会出现在我的日期字段的前一个额外的0?很抱歉的新手问题:(
Why is there an extra '0' in front of my date field? Sorry for the newbie question :(
修改:此code解决我的问题。感谢所有谁帮助。
EDIT This code solved my problem. Thanks to all who helped.
awk 'BEGIN {FS=","};{system("date")|getline myDate;printf "%i\t%i\t%s",$1, $2, myDate}' /dev/cu.usbmodem3d11
我不清楚为什么,但为了使日期不断更新并记录收到什么时候的数据,我不得不使用系统(DATE)
,而不仅仅是日期
在上面的code。
I'm not clear why, but in order for the date to keep updating and recording at what time the data was received, I have to use system("date")
instead of just "date"
in the code above.
推荐答案
2的事情
这将是更容易地看到你的问题,如果你添加一个 \\ n
你的的printf
字符串的结尾
It will be easier to see your problem if you add a \n
at the end of your printf
string
然后输出
>echo '1,2' | awk 'BEGIN {RS=","};{printf "%i\t%i\t%s\n",$1,$2,system("date")}'
Wed Feb 26 21:30:17 CST 2014
1 0 0
Wed Feb 26 21:30:17 CST 2014
2 0 0
我猜测,从系统输出(DATE)
返回其输出awk的范围外 $ 1,0
输入的每一行处理的自然范围。其他人可能能够提供一个更好的解释。
I'm guessing that output from system("date")
returns its output "outside" of scope of awk's $0
natural scope of each line of input processed. Others may be able to offer a better explanation.
要得到你想要的输出,我使用了函数getline
功能捕捉最新的输出
命令给一个变量( myDt
)。现在输出为
To get the output you want, I'm using the getline
function to capture the output of the date
command to a variable (myDt
). Now the output is
> echo '1,2' | awk 'BEGIN {RS=","};{"date" | getline myDt ; printf "%i\t%i\t%s\n",$1,$2,myDt}'
1 0 Wed Feb 26 21:31:15 CST 2014
2 0 Wed Feb 26 21:31:15 CST 2014
最后,我们删除了调试 \\ n
字符,并得到您所指定的输出:
Finally, we remove the "debugging" \n
char, and get the output you specify:
> echo '1,2' | awk 'BEGIN {RS=","};{"date" | getline myDt ; printf "%i\t%i\t%s",$1,$2,myDt}'
1 0 Wed Feb 26 21:34:56 CST 2014
2 0 Wed Feb 26 21:34:56 CST 2014
和每Jaypal的帖子,我现在看到 FS =,
是另一个问题,所以当我们做出的改变,并返回'\\ n'字符,我们有
And, per Jaypal's post, I see now that FS=","
is another issue, so when we make that change AND return the `\n' char, we have
echo '1,2' | awk 'BEGIN {FS=","};{"date" | getline myDt ; printf "%i\t%i\t%s\n",$1,$2,myDt}'
1 2 Wed Feb 26 21:44:42 CST 2014
这篇关于阅读使用awk串行输入,插入日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!