-3

I have this file, I want to print all the lines that are not of size 21.

PASY$ type a.a
000008050110010201NNN
000008060810010201NNN
21212000008070110010201NNN
000008080310010201NNN
000008090510010201NNN
000008050110010201NNN
000008060310010201NNN
00008070110010201NNN
Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
Ahmad S
  • 1
  • 1

2 Answers2

1
$ sed '/^.\{21\}$/d;q' input-file

sed will delete (and therefore not print) the first line with precisely 21 characters between the beginning and end of the line (the actual file will not be modified despite the use of scary words like "delete"). If such a line is found, it immediately will stop processing further lines.

DopeGhoti
  • 73,792
  • 8
  • 97
  • 133
  • DopeGhoti how can i get out of the sed one a single sed matching record is found . in my case as soon as a record that is not of size 21 is found i want to report and exit sed. – Ahmad S May 16 '18 at 18:59
  • By using the `q` command as I will shortly illustrate in an edit to my answer. – DopeGhoti May 16 '18 at 19:16
  • 1
    @AhmadS Your question asks specifically to _print all lines_ that are not 21 characters long. You are changing the question as you go. – Kusalananda May 16 '18 at 19:24
0
sed -n '/^.....................$/!p' < input-file

If there are not 21 characters between the beginning (^) of the line and the end ($) of the line, print it.

More positively, delete lines that are 21 characters long (printing other lines by default):

sed '/^.....................$/d' < input-file
Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
  • Why `sed 'stuff' < file` rather than just `sed 'stuff' file`? – DopeGhoti May 16 '18 at 17:19
  • Took me a minute to track it back down, but I've started leaning towards that habit after reading [this answer from Stéphane on input redirection](https://unix.stackexchange.com/a/70759/117549). It's also a small visual reminder that we're not attempting to *edit* the file (which `sed -i` or other utilities might do). – Jeff Schaller May 16 '18 at 17:30
  • Interesting read, but I'd probably end up leaning the other way so that I don't end up trying to `tool args < file1 file2` which won't work unless the tool in question is really smart about handling _both_ stdin _and_ file arguments at the same time. – DopeGhoti May 16 '18 at 17:34
  • yes this is exactly what i wanted . but can i get out of sed at the very first not match ? i dont want it scanning the whole file . – Ahmad S May 16 '18 at 18:39
  • You should edit the question (ideally, when initially asking it) to clarify that requirement. Most simply, tack on a ... `| head -1` – Jeff Schaller May 16 '18 at 19:03
  • Or `sed '/re/p;q' file`. – DopeGhoti May 16 '18 at 19:14
  • @AhmadS You have to scan the whole file if you want to print all lines that are not 21 characters. – Kusalananda May 16 '18 at 19:27