使用 xsel 将多行合并为一行

merge multiple lines into a single line using xsel

我想突出显示一个段落,然后执行 xsel。 很多时候,xsel 输出多行

$ xsel
The TCP/IP protocol suite is so named for two of its most important protocols: 
Transmission Control Protocol (TCP) and Internet Protocol (IP). A less used 

name for it is the Internet Protocol Suite, which is the phrase used in official 

Internet standards documents. In this book, we use the more common, shorter 

term, TCP/IP, to refer to the entire protocol suite.
\ No newline at end of selection

我想把它变成一行:

$ xsel
The TCP/IP protocol suite is so named for two of its most important protocols: Transmission Control Protocol (TCP) and Internet Protocol (IP). A less used name for it is the Internet Protocol Suite, which is the phrase used in official Internet standards documents. In this book, we use the more common, shorter term, TCP/IP, to refer to the entire protocol suite.
\ No newline at end of selection

有时,xsel 输出已经是单行。在这种情况下,无论我输入什么命令将多行转换为一行,都应该忽略这个难得的时刻。

您只需将 xsel 的输出重定向到某些实用程序,例如 tr 以将每个换行符转换为空白。

xsel | tr '\n' ' '

我将按如下方式使用 GNU AWK 完成此任务,令 xsel 输出为

The TCP/IP protocol suite is so named for two of its most important protocols: 
Transmission Control Protocol (TCP) and Internet Protocol (IP). A less used 

name for it is the Internet Protocol Suite, which is the phrase used in official 

Internet standards documents. In this book, we use the more common, shorter 

term, TCP/IP, to refer to the entire protocol suite.

然后

xsel | awk 'BEGIN{RS="[[:space:]]*\n+";ORS=" "}{print}'

输出

The TCP/IP protocol suite is so named for two of its most important protocols: Transmission Control Protocol (TCP) and Internet Protocol (IP). A less used name for it is the Internet Protocol Suite, which is the phrase used in official Internet standards documents. In this book, we use the more common, shorter term, TCP/IP, to refer to the entire protocol suite.

解释:我将行分隔符 (RS) 设置为 0 个或多个白色 spaces 后跟 1 个或多个换行符,并将行分隔符 (ORS) 设置为单个 space。这将防止多个 space 以防行尾有白色 space 并且行为空白。

(在 gawk 4.2.1 中测试)