How to remove lines shorter than XY?

You could use sed. The following would remove lines that are 3 characters long or smaller:

sed -r '/^.{,3}$/d' filename

In order to save the changes to the file in-place, supply the -i option.

If your version of sed doesn't support extended RE syntax, then you could write the same in BRE:

sed '/^.\{,3\}$/d' filename

which would work with all sed variants.


You could also use awk:

awk 'length($0)>3' filename

Using perl:

perl -lne 'length()>3 && print' filename

Some more variations:

grep .... file

or

sed '/..../!d' file

or

sed -n 's/./&/4p' file

or

awk 'gsub(/./,"&")>3' file

or

awk 'length>3' file

or GNU awk:

awk 'NF>3' FS= file

Here is the Vim solution using Vim's Ex mode and the global command.

This is very similar to using sed, only that some special chars ('{', '}') need to be escaped.

:g/^.\{,3\}$/d

Using Vim's Very Magic Regex mode (\v), this escaping can be avoided.

:g/\v^.{,3}$/d

See also :help magic

Use of "\v" means that in the pattern after it all ASCII characters except
'0'-'9', 'a'-'z', 'A'-'Z' and '_' have a special meaning.  "very magic"

Also sometimes useful is to do the opposite with vglobal.

:v/\v^.{,3}$/d

would delete everything but lines till 3 chars.