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

413 views Asked by At

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.

5

There are 5 answers

0
deepakchethan On BEST ANSWER

You can use awk:

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

You could use paste

paste -d, - - < file.txt

With pr

pr -ta2s, file.txt

with ed

ed -s file.txt <<-'EOF'
  g/./s/$/,/\
  ;.+1j
  ,p
  Q
EOF
1
Michael Discenza On

Take a look at 'paste'. This will join multiple lines of text together into a single line and should work for what you want.

echo "${DATA}"
Name
SANISGA01CI
5WWR031
P59CSADB01
CPDEV02

echo "${DATA}"|paste -sd ',' -
Name,SANISGA01CI,5WWR031,P59CSADB01,CPDEV02
0
James Brown On

Another awk:

$ awk -v OFS=, '{printf "%s%s",$0,(NR%2?OFS:ORS)}' file

Output:

47,1400
75,3800

Explained:

$ awk -v OFS=, '{        # set output field delimiter to a comma
    printf "%s%s",       # using printf to control newline in output
        $0,              # output line
        (NR%2?OFS:ORS)   # and either a comma or a newline
}' file
3
Paul Hodges On

Since you asked if a bash script can do this, here's a solution in pure bash. ;o]

c=0
while read -r line; do
  if (( c++ % 2 )); then
    echo "$line"
  else printf "%s," "$line"
  fi
done < file