
Extract Records from a text file
It's not really clear whether you want the "extracted" lines to be in
the new file or the remaining lines to be in the new file. If for items
i and ii you want the new file to just contain the selected lines, and
for items 111 and iv you want the input file to end up with the selected
lines removed, then these awk scripts should do the job:
i)
gawk -vstart=100 -vend=400 '
function printout(_str) { _out[++_nr] = _str }
function flushout( _i) { close("newfile");
for (_i=1; _i<=_nr;_i++)
print _out[_i] > "newfile"
}
NR>=start && NR<=end { printout( $0 ) }
END { flushout() }'
ii)
gawk -vpat="xyz" -vstart=8 -vend=10'
function printout(_str) { _out[++_nr] = _str }
function flushout( _i) { close("newfile");
for (_i=1; _i<=_nr;_i++)
print _out[_i] > "newfile"
}
substr($0,8,(end + 1 - start)) == pat { printout( $0 ) }
END { flushout() }'
iii)
gawk -vstart=100 -vend=400 '
function printout(_str) { _out[++_nr] = _str }
function flushout( _i) { close(FILENAME);
for (_i=1; _i<=_nr;_i++)
print _out[_i] > FILENAME
}
NR<start || NR>end { printout( $0 ) }
END { flushout() }'
iv)
gawk -vpat="xyz" -vstart=8 -vend=10'
function printout(_str) { _out[++_nr] = _str }
function flushout( _i) { close(FILENAME);
for (_i=1; _i<=_nr;_i++)
print _out[_i] > FILENAME
}
substr($0,8,(end + 1 - start)) != pat { printout( $0 ) }
END { flushout() }'
You could optimise the first 2 of them but they should get the job done.
Regards,
Ed.