How to convert rows to columns in unix

2020-02-29 11:29发布

I want my Unix file output, which has each value output on a new line, to be converted into grouped rows as shown below.

Say my output file in Unix looks like this:

jobname
userid
starttime
endtime
jobname2
userid
starttime
endtime

I want the output to be:

jobname1 userid starttime endtime
jobname2 userid starttime endtime

标签: unix
5条回答
够拽才男人
2楼-- · 2020-02-29 11:58

With GNU sed:

tr '\n' ' ' < file | sed -r 's/(\w+ +){4}/&\n/g'
查看更多
叼着烟拽天下
3楼-- · 2020-02-29 12:03

This is a minimal awk solution:

awk 'ORS=NR%4?" ":"\n"' input.txt 

output

jobname userid starttime endtime
jobname2 userid starttime endtime

(If you want to align the fields, pipe to column -t)

查看更多
劫难
4楼-- · 2020-02-29 12:14

This will paste each four consecutive lines as four tab-delimited fields:

cat source_file | paste - - - - > destination_file
查看更多
我想做一个坏孩纸
5楼-- · 2020-02-29 12:16

If you are looking for a shell script, you can do this as the number of lines to be printed in the output seems to have to fixed length:

while read line1; do
  read line2
  read line3
  read line4
  echo $line1 $line2 $line3 $line4 >>output
done <file
查看更多
别忘想泡老子
6楼-- · 2020-02-29 12:23

Kind of ugly, but doesn't require a shell script:

cat outputfile | tr "\n" " " | sed -e 's/\W*\(\w*\) \(\w*\) \(\w*\) \(\w*\)\W*/\1 \2 \3 \4\n/g'
查看更多
登录 后发表回答