-3

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.

Siva
  • 9,017
  • 8
  • 56
  • 86
Ahmad S
  • 1
  • 1
  • i have the sed command i am not sure how to break out of it . – Ahmad S May 16 '18 at 19:00
  • 1
    Possible duplicate of [sed command to find lines which are not of specific size](https://unix.stackexchange.com/questions/444204/sed-command-to-find-lines-which-are-not-of-specific-size) – DopeGhoti May 16 '18 at 19:31
  • In fairness, this is a duplicate of what the other question was apparently _meant_ to be as opposed to what the other question is _stated_ to be. – DopeGhoti May 16 '18 at 19:50

3 Answers3

1

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
Kusalananda
  • 320,670
  • 36
  • 633
  • 936
1

Based on this answer to your previous question

sed -n '/^.\{21\}$/! {p;q;}' file
steeldriver
  • 78,509
  • 12
  • 109
  • 152
1

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)

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501