如何使用 space 和逗号连接行

How do I join lines using space and comma

我的文件包含如下内容:

IP
111
22
25

我想以 IP 111,22,25.

格式打印输出

我已经尝试了 tr ' ' , 但它不起作用

以下 awk 脚本将执行请求:

awk 'BEGIN{OFS=","} FNR==1{first=[=10=];next} {val=val?val OFS [=10=]:[=10=]} END{print first FS val}' Input_file

说明:现在为上面的代码添加说明。

awk '                      ##Starting awk program here.
BEGIN{                     ##Starting BEGIN section here of awk program.
  OFS=","                  ##Setting OFS as comma, output field separator.
}                          ##Closing BEGIN section of awk here.
FNR==1{                    ##Checking if line is first line then do following.
  first=[=11=]                 ##Creating variable first whose value is current first line.
  next                     ##next keyword is awk out of the box keyword which skips all further statements from here.
}                          ##Closing FNR==1 BLOCK here.
{                          ##This BLOCK will be executed for all lines apart from 1st line.
  val=val?val OFS [=11=]:[=11=]    ##Creating variable val whose values will be keep concatenating its own value.
}
END{                       ##Mentioning awk END block here.
  print first FS val       ##Printing variable first FS(field separator) and variable val value here.
}' Input_file              ##Mentioning Input_file name here which is getting processed by awk.

尝试cat file.txt | tr '\n' ',' | sed "s/IP,/IP /g"

tr 删除新行,sedIP,111,22,25 更改为 IP 111,22,25

纯Bash:

# Read file into array
mapfile -t lines < infile

# Print to string, comma-separated from second element on
printf -v str '%s %s' "${lines[0]}" "$(IFS=,; echo "${lines[*]:1}")"

# Print
echo "$str"

输出:

IP 111,22,25

我会选择:

{ read a; read b; read c; read d; } < file
echo "$a $b,$c,$d"

这也有效:

xargs printf "%s %s,%s,%s" < file

使用 Perl

$ cat captain.txt
IP
111
22
25

$ perl -0777 -ne ' @k=split(/\s+/); print $k[0]," ",join(",",@k[1..$#k]) ' captain.txt
IP 111,22,25
$

欢迎来到paste

$ paste -sd " ," file
IP 111,22,25

通常 paste 所做的是写入标准输出行,这些行由每个给定文件的顺序对应行组成,由 字符分隔。选项 -s 的做法不同。它声明以 字符作为分隔符顺序粘贴文件的每一行。使用 -d 标志时,您可以给出要使用的分隔符列表,而不是 字符。在这里我给出了一个列表 " ," 表示,使用 space 然后只使用逗号。