Mehdi
Mehdi

Reputation: 1296

split file address in shell script by special character

I am writing a shell script. I have the file address in the following format:

/Users/hsn15051/downloads/RandomName1/RandomName2/SN/RandomNumber/Myimage.jpg 

I want to use the SN parameter which is always fixed so as to split the file address and have the following two strings

/Users/hsn15051/downloads/RandomName1/RandomName2/SN
/RandomNumber/Myimage.jpg

How can I do that?

Upvotes: 0

Views: 52

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84559

If you are using bash, you can use the capabilities of bash itself, parameter expansion with substring removal to parse the values you need:

end="${str##*/SN}"   ## get end
begin="${str%$end}"  ## remove end to get begin

This requires no additional subshell or utility.

A short example using your values:

#!/bin/bash

str="/Users/hsn15051/downloads/RandomName1/RandomName2/SN/RandomNumber/Myimage.jpg" 

end="${str##*/SN}"   ## get end
begin="${str%$end}"  ## remove end to get begin

printf "begin: %s\nend  : %s\n" "$begin" "$end"

Example Use/Output

$ bash splitstr.sh
begin: /Users/hsn15051/downloads/RandomName1/RandomName2/SN
end  : /RandomNumber/Myimage.jpg

Upvotes: 1

Gilles Quénot
Gilles Quénot

Reputation: 185179

$ sed -E 's|(.*/SN)(/.*)|\1\n\2|' <<< /Users/hsn15051/downloads/RandomName1/RandomName2/SN/RandomNumber/Myimage.jpg 

Output:

/Users/hsn15051/downloads/RandomName1/RandomName2/SN
/RandomNumber/Myimage.jpg

As you can see, you can choose your substitution delimiter, not mandatory to use s///

Edit :

Try this with the same input as :

perl -pe 's|(.*/SN)(/.*)|$1\n$2|'

Upvotes: 1

Related Questions