我在linux中有一个名为1.txt的文件,有多行,需要合并每三行
成一行。我已经提到了下面的输出,需要知道如何做到这一点
[xxx@c0040229 ~]$ cat 1.txt
c0043726.xxx.xx
50G,3.6G,44G,8%,/opt/tibco
200K,/opt/tibco/scripts
c0043725.xxx.xx
50G,9.5G,38G,21%,/opt/tibco
196K,/opt/tibco/scripts
c0043724.xxx.xx
50G,1.6G,46G,4%,/opt/tibco
92K,/opt/tibco/scripts
输出应
c0043726.xxx.xx,50G,3.6G,44G,8%,/opt/tibco,200K,/opt/tibco/scripts
c0043725.xxx.xx,50G,9.5G,38G,21%,/opt/tibco,196K,/opt/tibco/scripts
c0043724.xxx.xx,50G,1.6G,46G,4%,/opt/tibco,92K,/opt/tibco/scripts
有人能帮助我吗?
答案 0 :(得分:3)
我认为你可以用paste命令实现你想要的东西:
cat 1.txt | paste -d',' - - -
答案 1 :(得分:1)
使用paste
命令并将stdin(-
)作为输入三次输入:
$ cat 1.txt
c0043726.xxx.xx
50G,3.6G,44G,8%,/opt/tibco
200K,/opt/tibco/scripts
c0043725.xxx.xx
50G,9.5G,38G,21%,/opt/tibco
196K,/opt/tibco/scripts
c0043724.xxx.xx
50G,1.6G,46G,4%,/opt/tibco
92K,/opt/tibco/scripts
$ paste -d, - - - < 1.txt
c0043726.xxx.xx,50G,3.6G,44G,8%,/opt/tibco,200K,/opt/tibco/scripts
c0043725.xxx.xx,50G,9.5G,38G,21%,/opt/tibco,196K,/opt/tibco/scripts
c0043724.xxx.xx,50G,1.6G,46G,4%,/opt/tibco,92K,/opt/tibco/scripts
粘贴通常用于“粘贴 - 合并相应或后续的文件行”,如果使用stdin三次进行粘贴,则可以获得所需的效果。
答案 2 :(得分:0)
一个简单的脚本也可以实现你想要的。读取数据文件,然后将3行合并为一行。输出下方只是回显到屏幕上进行说明,但您可以使用echo
追加运算符将每个>>
语句重定向到一个文件。这使用case语句和简单的计数器。您可以使用$cnt % 3
模运算符来保存一行或两行来测试第3行。这是一个简短的例子:
#!/bin/bash
declare -i cnt=0
while IFS=$'\n' read -a line || test -n "$line"; do
((cnt++))
case "$cnt" in
[1-2] ) echo -n "$line,";;
3 ) echo "$line"; cnt=0;;
esac
done < "$1"
exit 0
<强>输出:强>
$ ./3lines.sh dat/3line.dat
c0043726.xxx.xx,50G,3.6G,44G,8%,/opt/tibco,200K,/opt/tibco/scripts
c0043725.xxx.xx,50G,9.5G,38G,21%,/opt/tibco,196K,/opt/tibco/scripts
c0043724.xxx.xx,50G,1.6G,46G,4%,/opt/tibco,92K,/opt/tibco/scripts
答案 3 :(得分:0)
你可以使用 awk&#39; NR%3!= 0 {printf $ 0; printf&#34; &#34;} NR%3 == 0 {print&#34; &#34;}&#39; FILENAME.TXT