bash:将五行输入组合到输出的每一行 [英] bash: combine five lines of input to each line of output

查看:37
本文介绍了bash:将五行输入组合到输出的每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入文件,如下所示:

I have a input file as follows:

MB1 00134141 
MB1 12415085 
MB1 13253590
MB1 10598105
MB1 01141484
...
...
MB1 10598105

我想合并5行并将其合并为一行.我希望我的bash脚本处理bash脚本以产生如下输出-

I want to combine 5 lines and merge it into one line. I want my bash script to process the bash script to produce output as follows -

MB1 00134141 MB1 12415085 MB1 13253590 MB1 10598105 MB1 01141484
...
...
...                                                 

我写了以下脚本,它可以工作,但是对于23051行大小的文件来说速度很慢.我可以编写更好的代码来使其更快吗?

I have written following script and it works but it is slow for file of size 23051 lines. Can I write a better code to make it faster?

#!/bin/bash
file=timing.csv
x=0
while [ $x -lt $(cat $file | wc -l) ]
do
   line=`head -n $x $file | tail -n 1`
   echo -n $line " "
   let "remainder = $x % 5"
   if [ "$remainder" -eq 0 ] 
   then
        echo ""
   fi
   let x=x+1
done
exit 0

我试图执行以下命令,但它弄乱了一些数字.

I tried to execute the following command but it messes up some numbers.

cat timing_deleted.csv | pr -at5

推荐答案

在纯bash中,没有外部进程(为了提高速度):

In pure bash, with no external processes (for speed):

while true; do
  out=()
  for (( i=0; i<5; i++ )); do
    read && out+=( "$REPLY" )
  done
  if (( ${#out[@]} > 0 )); then
    printf '%s ' "${out[@]}"
    echo
  fi
  if (( ${#out[@]} < 5 )); then break; fi
done <input-file >output-file

这可以正确处理行数不是5的倍数的文件.

This correctly handles files where the number of lines is not a multiple of 5.

这篇关于bash:将五行输入组合到输出的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆