Split String in Unix Script Shell

I have a line like this

//ABC/REC/TLC/SC-prod/1f9/20/00000000957481f9-08d035805a5c94bf 

and want to get the last part

00000000957481f9-08d035805a5c94bf
+3
source share
7 answers

Let's say you have

text="//ABC/REC/TLC/SC-prod/1f9/20/00000000957481f9-08d035805a5c94bf"

If you know the position, that is, in this case on the 9th, you can go with

echo "$text" | cut -d'/' -f9

However, if it is dynamic and you want to split by "/", it is safer to go with:

echo "${text##*/}"

This removes everything from the beginning to the last occurrence of "/" and should be the shortest to execute it.

See: Bash Reference Guide for more on this.

For more information, cutsee cut help page

+14
source

The tool basenamedoes just that:

$ basename //ABC/REC/TLC/SC-prod/1f9/20/00000000957481f9-08d035805a5c94bf  
00000000957481f9-08d035805a5c94bf
+6
source

bash string:

$ string="//ABC/REC/TLC/SC-prod/1f9/20/00000000957481f9-08d035805a5c94bf"

$ echo "${string##*/}"
00000000957481f9-08d035805a5c94bf

:

$ awk -F'/' '$0=$NF' <<< "$string"
00000000957481f9-08d035805a5c94bf

$ sed 's#.*/##g' <<< "$string"
00000000957481f9-08d035805a5c94bf

: <<< herestring. , POSIX sh ( , ).

+2

BASH regex:

s='//ABC/REC/TLC/SC-prod/1f9/20/00000000957481f9-08d035805a5c94bf'
[[ "$s" =~ [^/]+$ ]] && echo "${BASH_REMATCH[0]}"
00000000957481f9-08d035805a5c94bf
+1

awk:

string="//ABC/REC/TLC/SC-prod/1f9/20/00000000957481f9-08d035805a5c94bf"

echo "${string}" | awk -v FS="/" '{ print $NF }'

"/" .

+1

...

echo //ABC/REC/TLC/SC-prod/1f9/20/00000000957481f9-08d035805a5c94bf |awk -F "/" '{print $NF}'
0

, , - :

  echo $PWD | rev | cut -d'/' -f1-2 | rev
0

All Articles