Home > Blockchain >  Bash script - split String in two variables
Bash script - split String in two variables

Time:10-29

In a Bash script I want to split a string into two other strings based on the last "/" it contains.

In a situation where the given string is "Example/Folder/Structure", I would like to create two other strings with the following values:

string 1 = "Example/Folder"
string 2 = "Structure"

I'm trying to create a script to get a slather coverage report for a given folder in an iOS app. Although I have minimal knowledge of Bash, I was able to get it to work when the given folder is located in the root of the project. Now I want to make the script able to handle paths so that I can get the report also for subfolders, and for that I need to differentiate the desired folder from the rest of the path.

CodePudding user response:

basename(1), dirname(1):

path=a/b/c
basename=$(basename "$path") # c
dirname=$(dirname "$path")   # a/b

Prefix/suffix removal:

path=a/b/c
basename=${path##*/}         # c
dirname=${path%/*}           # a/b
  • Prefix/suffix removal is sufficient in some circumstances, and faster because it's native shell.
  • dirname/basename commands are slower (especially many paths in a loop etc) but handle more variable input or directory depth.
  • Eg. dirname "file" prints ., but suffix removal would print file. dirname /dir prints /, but suffix removal prints empty string; dirname also handles contiguous slashes (dirname a//b); basename a/b/ prints b, but prefix removal prints empty string.
  • If you know the structure is always 3 slashes (a/b/c), it may be safe to use prefix/suffix removal. But here I would use basename and dirname.
  • Also think about whether a better approach is to change the working directory with cd, so you can just refer to current directory with . (there's also $PWD and $OLDPWD).
  • Related