unix-剪切命令(添加自己的定界符) [英] unix - cut command (adding own delimiter)

查看:65
本文介绍了unix-剪切命令(添加自己的定界符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个包含这样数据的文件(即stores.dat文件)

Given a file with data like this (ie stores.dat file)

id               storeNo     type
2ttfgdhdfgh      1gfdkl-28   kgdl
9dhfdhfdfh       2t-33gdm    dgjkfndkgf

所需的输出:

id               |storeNo     |type
2ttfgdhdfgh      |1gfdkl-28   |kgdl
9dhfdhfdfh       |2t-33gdm    |dgjkfndkgf

想添加一个"|"这三个切割范围之间的定界符:

Would like to add a "|" delimiter between each of these 3 cut ranges:

cut -c1-18,19-30,31-40 stores.dat

在每个切割之间插入定界符的语法是什么?

What is the syntax to insert a delimiter between each cut?

奖金点(如果您可以提供这样的选项来修整值):

BONUS pts (if you can provide the option to trim the values like so):

id|storeNo|type
2ttfgdhdfgh|1gfdkl-28|kgdl
9dhfdhfdfh|2t-33gdm|dgjkfndkgf\

更新(感谢Mat的回答),我最终在该解决方案上取得了成功-(虽然有点混乱,但是带有bash版本的SunOS似乎不支持更优雅的算法)

#!/bin/bash
unpack=""
filename="$1"
while [ $# -gt 0 ] ; do
    arg="$1"
    if [ "$arg" != "$filename" ]
    then
        firstcharpos=`echo $arg | awk -F"-" '{print $1}'`
        secondcharpos=`echo $arg | awk -F"-" '{print $2}'`
        compute=`(expr $firstcharpos - $secondcharpos)`
        compute=`(expr $compute \* -1 + 1)`
        unpack=$unpack"A"$compute
    fi
    shift
done
perl -ne 'print join("|",unpack("'$unpack'", $_)), "\n";' $filename 

用法:sh test.sh input_file 1-17 18-29 30-39

Usage: sh test.sh input_file 1-17 18-29 30-39

推荐答案

如果您不害怕使用perl,这里有一个单行代码:

If you're not afraid of using perl, here's a one-liner:

$ perl -ne 'print join("|",unpack("A17A12A10", $_)), "\n";' input 

unpack 调用将从输入行中提取一个17个字符的字符串,然后一个12个字符的字符串,然后一个10个字符的字符串,然后将它们返回到数组中(带空格). join 添加 | .

The unpack call will extract one 17 char string, then a 12 char one, then a 10 char one from the input line, and return them in an array (stripping spaces). join adds the |s.

如果您希望输入列采用 x-y 格式,而无需编写真实"脚本,则可以像这样修改它(但很丑陋):

If you want the input columns to be in x-y format, without writing a "real" script, you could hack it like this (but it's ugly):

#!/bin/bash
unpack=""

while [ $# -gt 1 ] ; do
    arg=$(($1))
    shift
    unpack=$unpack"A"$((-1*$arg+1))
done

perl -ne 'print join("|",unpack("'$unpack'", $_)), "\n";' $1 

用法: t.sh 1-17 18-29 30-39 input_file .

这篇关于unix-剪切命令(添加自己的定界符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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