簡體   English   中英

SED和AWK在一行中的文件中打印條目

[英]SED & AWK print entries in a file on one line

我有一堆從腳本命令輸出中獲得的用戶名。 它們一個接一個地列出,我想一次在一行上打印5個

我的輸入是

eli
mo
joes
hope
tom
bob
smith
etc 
etc 
oinky

我希望輸出看起來像這樣

eli, mo, joes, hope, tom
bob, smith, etc, etc, oinky

你能幫忙嗎?

干杯

用awk:

awk '{if (NR%5 != 0) {printf $1", "} else {printf $1"\n"}}' file

更加尷尬的方式,感謝@JS웃

awk 'NR%5{printf "%s, ",$0;next}1' file

或者來自@Jotne的這個,我覺得不錯:

awk '{printf "%s"(NR%5?", ":"\n"),$1}' file
  • NR:基本上是記錄數,正在讀取的行數
  • %正在給您除法的其余部分

因此:

每5行打印文件的第一列($ 1,如果需要所有列則為$ 0)並創建新行,否則寫第一列和一個逗號。

(文件是您輸入的文件)

它給 :

eli, mo, joes, hope, tom
bob, smith, etc, etc, oinky

希望這可以幫助

your_command | paste - - - - - | sed 's/\t/, /g'
$ cat f
eli
mo
joes
hope
tom
bob
smith
etc 
etc 
oinky

最簡單的方法

$ awk 'ORS = !(NR%5)? RS : OFS' OFS=','  f
eli,mo,joes,hope,tom
bob,smith,etc ,etc ,oinky

要么

$ awk '{$1 = $1} ORS = !(NR%5)? RS : OFS' OFS=', '  f
eli, mo, joes, hope, tom
bob, smith, etc, etc, oinky
xargs -n 5 < yourfile | tr ' ' ','

可以說您的命令是cat fileName.txt ,它為您提供以下輸出:

eli
mo
joes
hope
tom
bob
smith
etc 
etc 
oinky

所以使用xargs命令,如下所示

貓fileName.txt | xargs -n 5 | sed -e's / /,/ g'

埃利,莫,喬斯,希望,湯姆

鮑勃,史密斯等,等等

獲得所需的輸出

這是我將如何使用awk做到這一點

awk '{printf "%s"(NR%5?", ":"\n"),$1}' file
eli, mo, joes, hope, tom
bob, smith, etc, etc, oinky

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM