Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string using a string as delimiter in awk

System : Solaris I am trying to split a string using the delimiter as another string

For example:


The main string is : /as/asdasd/asdasd/root/asdqwe/asd/asssdd/

I wanna split this into two part from the "root" substring such that

$1 = /as/asdasd/asdasd/

and

$2 = asdqwe/asd/asssdd/

This is the code I implemented using FS, but it doesn't work:

echo /as/asdasd/asdasd/root/asdqwe/asd/asssdd/ | awk '
BEGIN { FS = "root" } { print $2 }'
like image 317
tomkaith13 Avatar asked Mar 17 '11 00:03

tomkaith13


2 Answers

No need to use awk , you can do this with your POSIX shell like so:

$ var="/as/asdasd/asdasd/root/asdqwe/asd/asssdd/"

$ echo ${var%/root/*}
/as/asdasd/asdasd

$ echo ${var#*/root/}
asdqwe/asd/asssdd/

Update

If your Solaris version of awk isn't working (probably because FS must be chars not strings), then try this method using split()

awk '{split($0,a,"/root/");$1=a[1] "/"; $2=a[2]; print $1,$2}'
like image 60
SiegeX Avatar answered Sep 30 '22 09:09

SiegeX


It works here, aside from the extra / on the front which you don't handle. Maybe you want "root/" as your delimiter? It may also be necessary to use a newer awk; Solaris still ships the ancient V7 Unix awk as /usr/bin/awk, POSIX-compliant awk is /usr/bin/nawk.

like image 36
geekosaur Avatar answered Sep 30 '22 10:09

geekosaur