我的文件包含以下内容:
IP
111
22
25
我想以IP 111,22,25
格式打印输出。
我尝试过tr ' ' ,
,但是它不起作用
答案 0 :(得分:1)
在纯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
答案 1 :(得分:1)
我会选择:
{ read a; read b; read c; read d; } < file
echo "$a $b,$c,$d"
这也将起作用:
xargs printf "%s %s,%s,%s" < file
答案 2 :(得分:1)
欢迎来到paste
$ paste -sd " ," file
IP 111,22,25
通常paste
所做的是将其写入由每个给定文件的顺序对应行组成的标准输出行,并用-s
的作用不同。它声明以-d
标志时,可以提供要使用的定界符列表,而不是" ,"
,该列表指示使用空格,然后仅使用逗号。
答案 3 :(得分:0)
尝试cat file.txt | tr '\n' ',' | sed "s/IP,/IP /g"
tr
删除新行,sed
将IP,111,22,25
更改为IP 111,22,25
答案 4 :(得分:0)
使用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
$
答案 5 :(得分:-1)
以下awk脚本将执行请求的操作:
awk 'BEGIN{OFS=","} FNR==1{first=$0;next} {val=val?val OFS $0:$0} 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=$0 ##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 $0:$0 ##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.