how can I use sed
to report any first record that is not of size 21 in a file?
I don't want sed
to scan the complete file and get out as soon as the first record which is not of size 21 is found.
how can I use sed
to report any first record that is not of size 21 in a file?
I don't want sed
to scan the complete file and get out as soon as the first record which is not of size 21 is found.
Using awk
(this would be easiest):
awk 'length != 21 { printf("Line of length %d found\n", length); exit }' file
Or, as part of a shell script,
if ! awk 'length != 21 { exit 1 }' file; then
echo 'Line of length != 21 found (or awk failed to execute properly)'
else
echo 'All lines are 21 characters (or the file is empty)'
fi
Using sed
:
sed -nE '/^.{21}$/!{p;q;}' file
With GNU sed
, you would be able to do
if ! sed -nE '/.{21}$/!q 1' file; then
echo 'Line with != 21 characters found (or sed failed to run properly)'
else
echo 'All lines are 21 characters (or file is empty)'
fi
Based on this answer to your previous question
sed -n '/^.\{21\}$/! {p;q;}' file
With GNU grep
:
if line=$(grep -Exnvm1 '.{21}' < file); then
printf >&2 'Found "%s" which is not 21 characters long\n' "$line"
fi
(-n
above includes the line number)