按列将分隔文件拆分为较小的文件 [英] Split delimited file into smaller files by column

查看:33
本文介绍了按列将分隔文件拆分为较小的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉linux中的split命令.如果我有一个 100 行长的文件,

I'm familiar with the split command in linux. If I have a file that's 100 lines long,

split -l 5 myfile.txt

...将 myfile.txt 拆分为 20 个文件,每个文件有 5 行,并将它们写入文件.

...will split myfile.txt into 20 files, each having 5 lines, and will write them to file.

我的问题是,我想按列执行此操作.给定一个 100 列、制表符分隔的文件,是否有类似的命令将该文件拆分为 20 个较小的文件,每个文件有 5 列和所有行?

My question is, I want to do this by column. Given a file with 100 columns, tab delimited, is there a similar command to split this file into 20 smaller files, each having 5 columns and all the rows?

我知道如何使用 cut,但我希望有一个我从未听说过的简单 UNIX 命令可以在不使用 perl 或其他东西包装 cut 的情况下完成此操作.

I'm aware of how to use cut, but I'm hoping there's a simple UNIX command I've never heard of that will accomplish this without wrapping cut with perl or something.

提前致谢.

推荐答案

#!/bin/bash

(($# == 2)) || { echo -e "\nUsage: $0 <file to split> <# columns in each split>\n\n"; exit; }

infile="$1"

inc=$2
ncol=$(awk 'NR==1{print NF}' "$infile")

((inc < ncol)) || { echo -e "\nSplit size >= number of columns\n\n"; exit; }

for((i=0, start=1, end=$inc; i < ncol/inc + 1; i++, start+=inc, end+=inc)); do
  cut -f$start-$end "$infile" > "${infile}.$i"
done

这篇关于按列将分隔文件拆分为较小的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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