linux下删除文件中空行的多种方法

  • linux下删除文件中空行的多种方法已关闭评论
  • 32 views
  • A+
所属分类:linux

源文件:

$ cat a.txt
baiked.com is a best Linux blog to learn Linux.

It's FIVE years old blog.

This website is maintained by Magesh M, it's licensed under CC BY-NC 4.0.

He got two GIRL babys.

Her names are Tanisha & Renusha.

sed命令:

sed 是一个流编辑器。流编辑器是用来编辑输入流(文件或管道)中的文本的。

如下:

$ sed '/^$/d' a.txt
baiked.com is a best Linux blog to learn Linux.
It's FIVE years old blog.
This website is maintained by Magesh M, it's licensed under CC BY-NC 4.0.
He got two GIRL babes.
Her names are Tanisha & Renusha.

详解:

  • //: 标记匹配范围。
  • ^: 匹配字符串开头。
  • $: 匹配字符串结尾。
  • d: 删除匹配的字符串。
  • a.txt: 源文件名。

grep命令:

grep 可以通过正则表达式在文件中搜索。该表达式可以是一行或多行空行分割的字符,grep 会打印所有匹配的内容。

如下:

$ grep . a.txt
or
$ grep -Ev "^$" a.txt
or
$ grep -v -e '^$' a.txt
baiked.com is a best Linux blog to learn Linux.
It's FIVE years old blog.
This website is maintained by Magesh M, it's licensed under CC BY-NC 4.0.
He got two GIRL babes.
Her names are Tanisha & Renusha.

详解:

  • .: 替换任意字符。
  • ^: 匹配字符串开头。
  • $: 匹配字符串结尾。
  • E: 使用扩展正则匹配模式。
  • e: 使用常规正则匹配模式。
  • v: 反向匹配。
  • 2daygeek.txt: 源文件名。

awk 命令:

awk 可以执行使用 awk 语言写的脚本,大多是专用于处理文本的。awk 脚本是一系列 awk 命令和正则的组合。

$ awk NF a.txt
or
$ awk '!/^$/' a.txt
or
$ awk '/./' a.txt
baiked.com is a best Linux blog to learn Linux.
It's FIVE years old blog.
This website is maintained by Magesh M, it's licensed under CC BY-NC 4.0.
He got two GIRL babes.
Her names are Tanisha & Renusha.

详解:

  • //: 标记匹配范围。
  • ^: 匹配字符串开头。
  • $: 匹配字符串结尾。
  • .: 匹配任意字符。
  • !: 删除匹配的字符串。
  • a.txt: 源文件名。

cat 和 tr 命令 组合:

cat 是串联(拼接)的简写。经常用于在 Linux 中读取一个文件的内容。

tr 可以将标准输入中的字符转换,压缩或删除,然后重定向到标准输出。

$ cat a.txt | tr -s '\n'
baiked.com is a best Linux blog to learn Linux.
It's FIVE years old blog.
This website is maintained by Magesh M, it's licensed under CC BY-NC 4.0.
He got two GIRL babes.
Her names are Tanisha & Renusha.

详解:

  • |: 管道符号。它可以将前面的命令的标准输出作为下一个命令的标准输入。
  • s: 替换标数据集中任意多个重复字符为一个。
  • \n: 添加一个新的换行。
  • a.txt: 源文件名。

 

  • 安卓客户端下载
  • 微信扫一扫
  • weinxin
  • 微信公众号
  • 微信公众号扫一扫
  • weinxin
avatar