简体   繁体   中英

merge multiple lines into a single line using xsel

I want to highlight a paragraph and then do xsel . Often times, the xsel outputs multiple lines

$ 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

I would like to turn this into a single line:

$ 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

sometimes, the xsel output is already single line. In this instance, whatever command I put in to convert multiple lines into a single line should ignore this rare moment.

I would use GNU AWK for this task as follows, let xsel output be

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.

then

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

output

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.

Explanation: I set row separator ( RS ) to 0 or more whitespaces followed by 1 or more newline and output row separator ( ORS ) to single space. This will prevent multiple space in case line have trailing whitespace and in case line is blank.

(tested in gawk 4.2.1)

You just have to redirect the output of xsel to some utility like tr for translating each newline character into a blank.

xsel | tr '\n' ' '

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM