0

Input

dir/foo

Output

dir./

so I need:

echo 'dir/foo' | MAGIC

Q: What is MAGIC? (something like a cut+sed joined:D)

  • 1
    How many slashes will there be in "dir"? – glenn jackman Oct 7 '13 at 20:55
6

You have a few options here. My preference would be towards a parameter expansion:

foo=dir/foo
echo "${foo%/*}./"

Another option is awk:

echo "dir/foo" | awk -F/ '{ print $1"./" }'
4

Another use of read

IFS=/ read a b <<<"dir/foo"
echo "$a./"

Won't work if "dir/foo" is actually "/home/user/foo"

4

You can use also dirname with read

read foo
echo "$(dirname "$foo")./"

and dirname with xargs.

echo "$(xargs dirname)./"

Example usage with a function:

$ MAGIC() { echo "$(xargs dirname)./"; }
$ echo 'dir/foo' | MAGIC
dir./
  • I think you meant dirname. – terdon Oct 7 '13 at 21:26
  • @terdon: Oops. Fixed. – user26112 Oct 7 '13 at 21:32
4

I'm not sure what you're trying to do here. Do you really want a literal .? This feels like an XY problem.

Anyway, a simple way of doing what you seem to be asking is to use dirname:

$ echo $(dirname "dir/foo")./
dir./

The main advantages of dirname is that it can deal with spaces and is part of GNU coreutils so will be installed in all GNU systems. Also it can deal with arbitrarily long paths:

$ echo $(dirname "aa/bb bb/cc/foo")./
aa/bb bb/cc./

You can use @EvanTeitelman's trick to make this into a function:

$ MAGIC() { echo $(dirname "$1")./; }
$ MAGIC 'dir/foo'
dir./
$ MAGIC 'dir/foo bar/foo'
dir/foo bar./

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.