I have a data file with multiple data blocks enclosed between specific keywords (DATA
,END
). I am using awk
to extract the data blocks into separate files, based on a file name taken from said block.
Since some data blocks share the same name, I am renaming each output file with an increasing integer if the file ("blockname
") already exists:
#cat input.file
useless stuff1
DATA blockname1
data1
data1
END
useless stuff2
DATA blockname2
data2
data2
END
useless stuff3
DATA blockname1
data3
data3
END
useless stuff4
Expected would be three output files blockname1
, blockname2
, and blockname1_1
(note how the last file has an integer assigned to it)
#cat blockname1
DATA blockname1
data1
data1
END
(the others accordingly...)
Now the following script works as I want it:
awk '/DATA/,/END/ {
if ( $1 ~ /DATA/ )
{ block=$2 ; i=0 ; file=block
while ( system("test ! -e " file ) )
{ i++ ; file=block"_"i ; print file }
}
print $0 > file
}' input.file
My problem lies with the while
loop and its system call:
I expected system("test -e " file)
to be TRUE when the file
exists and to be FALSE if file
does not yet exist, i.e. the while
loop to only start running if file
is present and to break if (the new) file
does not exist yet.
However if I use system("test -e " file)
(and make it verbose with print file
), I have an infinite loop of the same name with increasing integer suffix and the opposite system("test !-e " file)
gives the desired result.
So this behaves exactly inverse to what I expected.