csvunix-text-processing

How to format a TXT file into a structured CSV file in bash?


I wanted to get some information about my CPU temperatures on my Linux Server (OpenSuse Leap 15.2). So I wrote a Script which collects data every 20 seconds and writes it into a text file. Now I have removed all garbage data (like "CPU Temp" etc.) I don't need.

Now I have a file like this:

47
1400
75
3800

The first two lines are one reading of the CPU temperature in C and the fan speed in RPM, respectively. The next two lines are another reading of the same measurements.

In the end I want this structure:

47,1400
75,3800

My question is: Can a Bash script do this for me? I tried something with sed and Awk but nothing worked perfectly for me. Furthermore I want a CSV file to make a graph, but i think it isn't a problem to convert a text file into a CSV file.


Solution

  • You can use awk:

    awk 'NR%2{printf "%s,",$0;next;}1' file.txt > file.csv