0

I'm building a small script to automate something I do pretty regularly.

The script takes in a single parameter, for example: vendor/package. I'd like to take that and split/explode it into two separate strings: vendor and package.

I've looked at solutions on here and various other places but can't get anything to work. I'm sure it's really simple but I'm not great at bash so some help would be greatly appreciated. Thanks!

Duncan McClean
  • 130
  • 2
  • 11
  • var='vendor/package'; IFS='/' read -r first second <<< "$var"; echo "first=$first"; echo "second=$second" – M. Nejat Aydin Feb 21 '21 at 12:53
  • 1
    @DuncanMcClean: You tagged this _bash_, _zsh_ and _shell_. Which one are you interested in? For instance, I would solve this problem differently in zsh than in POSIX shell or bash. – user1934428 Feb 22 '21 at 08:18

2 Answers2

1

You can use cut to achieve this

[ vaebhav@Vaibhavs-MacBook-Air:/usr/local/lib - 06:12 PM ]$ echo "value/package" | cut -d"/" -f1
value
[ vaebhav@Vaibhavs-MacBook-Air:/usr/local/lib - 06:12 PM ]$ echo "value/package" | cut -d"/" -f2
package
[ vaebhav@Vaibhavs-MacBook-Air:/usr/local/lib - 06:12 PM ]$ 

in terms of its implementation in a script -

part1=`echo $1 | cut -d"/" -f1`
part2=`echo $1 | cut -d"/" -f2`

Vaebhav
  • 4,672
  • 1
  • 13
  • 33
  • 1
    @DuncanMcClean This is overkill for this task. A simple `IFS='/' read -r part1 part2 <<< "$1"` would do the job much more efficiently using only a builtin command (`read`) in `bash`, without resorting to external commands and without creating subprocesses. – M. Nejat Aydin Feb 21 '21 at 13:11
0

If using bash:

#!/bin/bash
echo ${1#*/}
echo ${1%/*}

Test:

$ bash foo.bash vendor/package
package
vendor
James Brown
  • 36,089
  • 7
  • 43
  • 59