如何删除比XY短的线?

eva*_*ine 38 sed text-processing

我发现了一个关于如何删除超过 2048 个字符的行的问题:

如果长于XY,如何删除行?

问:但是如何删除短于 4 个字符的行?因此,删除文件中长度为 1 或 2 或 3 的行。

更新:感谢许多好的答案,但我只能将一个标记为 OK

dev*_*ull 52

你可以使用sed. 以下将删除长度为 3 个字符或更小的行:

sed -r '/^.{,3}$/d' filename
Run Code Online (Sandbox Code Playgroud)

为了就地保存对文件的更改,请提供该-i选项。

如果您的版本sed不支持扩展 RE 语法,那么您可以在 BRE 中编写相同的内容:

sed '/^.\{,3\}$/d' filename
Run Code Online (Sandbox Code Playgroud)

这将适用于所有sed变体。


您还可以使用awk:

awk 'length($0)>3' filename
Run Code Online (Sandbox Code Playgroud)

使用perl:

perl -lne 'length()>3 && print' filename
Run Code Online (Sandbox Code Playgroud)


Scr*_*zer 9

还有一些变化:

grep .... file
Run Code Online (Sandbox Code Playgroud)

或者

sed '/..../!d' file
Run Code Online (Sandbox Code Playgroud)

或者

sed -n 's/./&/4p' file
Run Code Online (Sandbox Code Playgroud)

或者

awk 'gsub(/./,"&")>3' file
Run Code Online (Sandbox Code Playgroud)

或者

awk 'length>3' file
Run Code Online (Sandbox Code Playgroud)

或 GNU awk:

awk 'NF>3' FS= file
Run Code Online (Sandbox Code Playgroud)

  • 哦那个 grep .... 太优雅了! (4认同)

小智 5

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
Run Code Online (Sandbox Code Playgroud)

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

:g/\v^.{,3}$/d
Run Code Online (Sandbox Code Playgroud)

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"
Run Code Online (Sandbox Code Playgroud)

Also sometimes useful is to do the opposite with vglobal.

:v/\v^.{,3}$/d
Run Code Online (Sandbox Code Playgroud)

would delete everything but lines till 3 chars.