shell - 如何用每个只有 1 个空行替换许多中间空行

标签 shell sed awk newline

我正在学习使用 sed 并且有一个假设需求:

bash$ cat states
California


Massachusetts


Arizona

Wisconsin

我想要输出:(基本上我只想要中间的一个空行)

California

Massachusetts

Arizona

Wisconsin

请建议使用 sed 的方法。 是否应该使用多行模式空间等概念?

谢谢,

猎豹


作为对其中一条评论的回应,好的,我运行了一些测试脚本,我错误地假设地址空间选择标准只应用一次。它似乎一次又一次地被激活。

bash$ cat file 
a 
b 
c 
a 
b 
c 

bash$ sed -e '/a/,/b/s/$/x/g' file 
ax 
bx 
c 
ax 
bx 
c 

我的印象是它会产生:

ax 
bx 
c 
a 
b 
c

有人可以解释 sed 在逗号分隔地址空间的情况下如何进行。

最佳答案

试试这个,它会删除所有连续的空行

cat states | sed '/./,/^$/!d'

输出:

California

Massachusetts

Arizona

Wisconsin

关于shell - 如何用每个只有 1 个空行替换许多中间空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3270618/

相关文章:

linux - 为什么这个 bash expr 命令不起作用?

sed - 使用 sed 或 awk 在特定行号处插入一行

awk - 从 bash 输出中提取字符串

linux - 将 tar 命令的输出重定向到 shell 脚本中的变量

linux - 查找具有多个文件扩展名的命令

bash - 使用一个命令的输出作为 sed 中的替换文本

linux - Linux 中通过 sed 匹配某些实例

perl - 文件中恰好需要 1 个尾随换行符

regex - 如何从 C 源文件中删除所有/* */注释?

node.js - 通过Shell脚本从ssh命令运行 Node 文件