advanced split in bash

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ciary
    Recognized Expert New Member
    • Apr 2009
    • 247

    advanced split in bash

    Hi,

    i'm not an expert in bash and i have a question. is there a way to split a string on a sequence of characters rather than just one?

    the idea is the following
    Code:
    workdir=`pwd`
    echo $workdir
    # /path/to/my/split/directory/i/want/
    arr=$(echo $workdir | tr "/split/" "\n")
    echo $arr[0]
    # /path/to/my
    echo $arr[1]
    # directory/i/want/
    this is not what this code actually does, but that's what i tried and wanted it to do. when i execute this, the string in workdir is actually split on all characters that match a character in "/split/"

    tnx
  • Ciary
    Recognized Expert New Member
    • Apr 2009
    • 247

    #2
    there is a workaround
    Code:
    workdir=`pwd`
    echo $workdir
    # /path/to/my/split/directory/i/want/
    temp=$(echo $workdir | sed "s/\/split\// /g")
    echo $temp
    # /path/to/my directory/i/want/
    arr=( $temp )
    echo ${arr[0]}
    # /path/to/my
    echo ${arr[1]}
    # directory/i/want/
    but there has to be a way to do this without the temp-variable, right?

    Comment

    • Luuk
      Recognized Expert Top Contributor
      • Mar 2012
      • 1043

      #3
      Code:
      #!/bin/bash
      
      workdir=/path/to/my/split/directory/i/want/
      echo "workdir: $workdir"
      p1=/split/*
      echo "1: " ${workdir/$p1}
      echo "workdir: $workdir"
      p2=*/split/
      echo "2: " ${workdir/$p2}
      output:
      Code:
      workdir: /path/to/my/split/directory/i/want/
      1:  /path/to/my
      workdir: /path/to/my/split/directory/i/want/
      2:  directory/i/want/
      read more on this in the man-page:
      ${parameter/pattern/string}
      Pattern substitution. The pattern is expanded to produce a pat-
      tern just as in pathname expansion. Parameter is expanded and
      the longest match of pattern against its value is replaced with
      string. If pattern begins with /, all matches of pattern are
      replaced with string. Normally only the first match is
      replaced. If pattern begins with #, it must match at the begin-
      ning of the expanded value of parameter. If pattern begins with
      %, it must match at the end of the expanded value of parameter.
      If string is null, matches of pattern are deleted and the / fol-
      lowing pattern may be omitted. If parameter is @ or *, the sub-
      stitution operation is applied to each positional parameter in
      turn, and the expansion is the resultant list. If parameter is
      an array variable subscripted with @ or *, the substitution
      operation is applied to each member of the array in turn, and
      the expansion is the resultant list.
      Last edited by Luuk; Nov 3 '12, 10:30 AM. Reason: man-page info added

      Comment

      Working...