Search code examples
bashshellscriptingechoxargs

bash substring from xargs piped


Reading how to get substring in bash, I found out the following commands works:

var="/aaa/bbb/ccc/ddd"
echo ${var##*/}

Which produces "ddd"

My complete problem is to make this dinamically reading from a pipe:

I want to achieve something like this:

echo /aaa/bbb/ccc/ddd | xargs echo ${MyVar##*/}

But it is not working.

I tried to use -I option follwing way:

echo /aaa/bbb/ccc/ddd | xargs -I MyVar echo ${MyVar##*/}

And did not work either, (I think it does not interpolate it)

Any way to solve this?

Is it posible to achieve also to read substring left part, instead of right part?


Solution

  • You may use it like this:

    echo '/aaa/bbb/ccc/ddd' | xargs -I {} bash -c 'echo "${1##*/}"' - {}
    

    ddd
    

    or just use awk:

    echo '/aaa/bbb/ccc/ddd' | awk -F/ '{print $NF}'