Is there a simple way with gnuplot to import data with fixed widths of the columns?
The problem is that columns could be empty, so importing with set datafile separator whitespace will not work correctly.
I'm aware that you can preprocess data with external tools like awk, sed, etc. but I'm wondering if there might be a simple platform independent gnuplot-only solution.
The solution I've come up with is a bit lengthy, but at least it seems to work. If there is a simpler gnuplot-way please let me know.
Code:
### data with fixed column widths
reset session
$DataRaw <<EOD
# Data with fixed but also empty columns
#0000000011111111112222222222333333333344444
#2345678901234567890123456789012345678901234
#--6-||----11---||--7--||-----12---||--8---|
1.1 1.2222 1.03 some Text 1.555
2.1 -2.2222 -2.555
-3.1 3.2222 -3.03 more text 3.555
4.1 -4.03 -4.555
no data 0.000
6.1 -6.2222 6.03 no comment -6.555
EOD
# define the widths of the columns
array FixCols[5] = [6,11,7,12,8]
set datafile separator "\n"
CommentChar = "#"
Separator = ','
# define strip() function workaround to remove spaces at beginning and end of a string
strip(s) = (STRP_a=1, STRP_b=1, \
sum [STRP_i=1:strlen(s)] ((s[STRP_i:STRP_i] eq " ") ? \
(STRP_a>0 ? STRP_a=STRP_a+1 : 0) : (STRP_a=-abs(STRP_a), STRP_b=STRP_i) \
), s[abs(STRP_a):STRP_b] )
set print $Data
do for [i=1:|$DataRaw|] {
if ($DataRaw[i][1:1] ne CommentChar) {
Line = ''
Start = 1
do for [j=1:|FixCols|] {
End = Start + FixCols[j]-1
Line = Line.strip($DataRaw[i][Start:End]).(j<|FixCols| ? Separator : "")
Start = Start + FixCols[j]
}
print Line
}
else { print $DataRaw[i]} # print the unchanged commented line
}
set print
print $Data
### end of code
Result:
# Data with fixed but also empty columns
#0000000011111111112222222222333333333344444
#2345678901234567890123456789012345678901234
#--6-||----11---||--7--||-----12---||--8---|
1.1,1.2222,1.03,some Text,1.555
2.1,-2.2222,,,-2.555
-3.1,3.2222,-3.03,more text,3.555
4.1,,-4.03,,-4.555
,,,no data,0.000
6.1,-6.2222,6.03,no comment,-6.555
