Narayana
Narayana

Reputation: 333

BASH/SED - Better way of removing the start and end of a string?

This is what I am currently using:

   echo /home/user/yolo/123/swag | sed 's,/home/user/,,' | sed 's,swag,,'

Is there a better way of doing this ?

Upvotes: 0

Views: 56

Answers (1)

choroba
choroba

Reputation: 242423

You can use parameter expansion in bash:

path=/home/user/yolo/123/swag
path=${path#/home/user/}       # Remove from left.
path=${path%swag}              # Remove from right.
echo "$path"

Update

For an array of paths, the code is quite similar:

path=(/home/user/file/1/swag /home/user/file/2/swag /home/user/different/path/swag)
path=(${path[@]#/home/user/})       # Remove from left.
path=(${path[@]%swag})              # Remove from right.
echo "${path[@]}"

Upvotes: 2

Related Questions