开发者

Split a string using a string as delimiter in awk

开发者 https://www.devze.com 2023-02-17 12:53 出处:网络
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/

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 /a开发者_JS百科s/asdasd/asdasd/root/asdqwe/asd/asssdd/ | awk '
BEGIN { FS = "root" } { print $2 }'


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}'


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消