Search code examples
shellawksedshcut

To get first and last occurrence when cut using a delimiter


I have a text file a.txt with following data

 abc/def/ghi  
 jkl/mno/pqr/stu

I need to cut them so that I get first and last string with "/" as delimiter

Output expected is

abc ghi
jkl stu


cat a.txt |cut -d "/" -f1               #gives me first cell
cat a.txt |rev |cut -d "/" -f1 |rev     #gives me last cell

I want both cells to be available in single command. Kindly help.


Solution

  • You could use awk for this,

    $ awk -F/ '{print $1,$NF}' file
    abc ghi  
    jkl stu
    

    Through sed,

    $ sed 's~^\([^/]*\).*\/\(.*\)$~\1 \2~g' file
    abc ghi  
    jkl stu
    

    Through perl,

    $ perl -pe 's;^([^/]*).*\/(.*)$;\1 \2;g' file
    abc ghi  
    jkl stu
    

    Ugly hack through grep and paste,

    $ grep -oP '^[^/]*|\w+(?=$)' file | paste -d' ' - -
    abc ghi
    jkl stu