How to get second last field from a cut command

前端 未结 6 2080
南方客
南方客 2020-12-04 19:04

I have a set of data as input and need the second last field based on deleimiter. The lines may have different numbers of delimiter. How can I get second last field ?

6条回答
  •  有刺的猬
    2020-12-04 19:52

    Code for GNU sed:

    $ echo text,blah,blaah,foo|sed -r 's/^(\S+,){2}(\S+),.*/\2/'
    blaah
    
    $ echo this,is,another,text,line|sed -r 's/^(\S+,){2}(\S+),.*/\2/'
    text
    

    Code example similar to sudo_O's awk code:

    $ sed -r 's/.*,(\w+),\w+$/\1/' file
    blaah
    text
    

    It might be better to use more specialised programs for CSV files, eg. awk or excel.

提交回复
热议问题