1

Let's say I have a string and its contents are US1SERVLOC2. I want to be able to get the strings US1 and LOC2 from that string.

echo "US1SERVLOC2" | cut -f1 -d 'SERV'
echo "US1SERVLOC2" | cut -f2 -d 'SERV'

I originally tried this but cut doesn't like delimiters that aren't single characters. How do I accomplish this?

DeadCake
  • 467
  • 1
  • 7
  • 18

2 Answers2

3

Try:

s=US1SERVLOC2
echo ${s%SERV*}  # prints US1
echo ${s#*SERV}  # prints LOC2

See:

Note:

  • %SERV* will cut SERV* from the end of s.
  • #*SERV will cut *SERV from the start of s.
  • If SERV appears multiple times, you can use %%/## instead of %/# to extend the matches. However, this will only allow you to cut at the first or last occurence of SERV. If that is not suitable, awk will gladly accept multi-character field separators:

    s=US1SERVLOC1US2SERVLOC2US3SERVLOC3
    echo $s | awk -F "SERV" '{print $2}'  # prints LOC1US2
    
Community
  • 1
  • 1
Matei David
  • 2,322
  • 3
  • 23
  • 36
2

Use built-in shell variable expansion operators.

var=US1SERVLOC2
part1=${var%SERV*}
part2=${var#*SERV}

However, these won't work the same as your attempted cut if SERV appears more than once in the string.

Barmar
  • 741,623
  • 53
  • 500
  • 612