Sufiyan Ghori Sufiyan Ghori - 5 months ago 16
Linux Question

awk command output to a text file

I know how to write the output of a simple awk code into a text file using

>
or append it in a text file using
>>


but the issue here is different,

here is my line of code whose output needs to be written in a text file,

stty -F /dev/ttyUSB0 ispeed 4800 && awk -F"," '/SUF/ {print $3,$4,$5,$6,$10,$11,substr($2,1,2),".",substr($2,3,2),".",substr($2,5,2)}' < /dev/ttyUSB0


here
-F
is used to define a field seperator, which is
,
, the above line aims to search for anything that matches SUF and prints its 3rd, 4th, 5th, 6th, 10th and 11th value ,
and some part of the 2nd value...these values are read from the USB device
/dev/ttyUSB0


the above command is working absolutely fine and giving the correct output,

Here is the example output,

SUF Third Fourth Fifth Sixth Tenth Eleventh AA.BB.CC
SUF Third Fourth Fifth Sixth Tenth Eleventh AA.BB.CC
SUF Third Fourth Fifth Sixth Tenth Eleventh AA.BB.CC
SUF Third Fourth Fifth Sixth Tenth Eleventh AA.BB.CC
SUF Third Fourth Fifth Sixth Tenth Eleventh AA.BB.CC
SUF Third Fourth Fifth Sixth Tenth Eleventh AA.BB.CC
SUF Third Fourth Fifth Sixth Tenth Eleventh AA.BB.CC


The problem is, the output won't stop coming, and it is in a form of something like an infinite loop and I have to press
CTRL+C
to terminate it.

Now the real issue,
How to write this output into a text file ?

Attempt:

I have tried this so far to write this output into a text file,

stty -F /dev/ttyUSB0 ispeed 4800 && awk -F"," '/SUF/ {print $3,$4,$5,$6,$10,$11,substr($2,1,2),".",substr($2,3,2),".",substr($2,5,2)}' < /dev/ttyUSB0 > outputfile.txt


it does create an output file called
outputfile.txt
, but it writes nothing inside it.

Which means I am not able to write the output in a text file at all. How am I supposed to write just first few lines of this output into a file text file ?

In case if isn't possible with terminal, is it possible to run the same command using Python and write the output to a text file and terminate it ?

Answer

Your output is probably buffered and you stop the code before the buffer is flushed. By forcing awk to only process several records, it will gracefully exit and write the buffered output.

Try forcing awk to process the first ten it encountered by checking the record count.

stty -F /dev/ttyUSB0 ispeed 4800 && awk -F"," '/SUF/ and NR < 10 {print $3,$4,$5,$6,$10,$11,substr($2,1,2),".",substr($2,3,2),".",substr($2,5,2)} NR > 9 {exit}' < /dev/ttyUSB0 > outputfile.txt

NR evaluates to the current record number relative to the first record read when awk started. When NR is greater than 9 it will exit. If you prefer to only print one occurrence of /SUF/ then you can immediately exit after the print.

stty -F /dev/ttyUSB0 ispeed 4800 && awk -F"," '/SUF/ {print $3,$4,$5,$6,$10,$11,substr($2,1,2),".",substr($2,3,2),".",substr($2,5,2); exit}' < /dev/ttyUSB0 > outputfile.txt