1

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?

Mayday
  • 4,680
  • 5
  • 24
  • 58
  • 1
    Keep it simple, maybe: `FOO=$(echo "/aaa/bbb/ccc/ddd") ; echo ${FOO##*/}`? So you would get the output from your pipe into a shell variable first, then apply the shell parse. It's not a one-liner, but it's simple. – lurker Nov 29 '18 at 16:28
  • Im not sure if i can do it that easy. The original output comes from a git status command, with multiple lines, which i am trying to apply the command 1 by 1 – Mayday Nov 29 '18 at 16:32
  • 1
    @Mayday: The answers in the duplicated question should solve your problem and you don't need to use `xargs` at all – Inian Nov 29 '18 at 16:38

2 Answers2

2

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}'
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

You can do this :

echo '/aaa/bbb/ccc/ddd' | sed -E 's/(.*\/)(.*)/\2/g' | xargs -n 1 $1

Hope it helps!

Matias Barrios
  • 4,674
  • 3
  • 22
  • 49