Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first part of string

How do I pull a substring from a string. For example, from the string:

'/home/auto/gift/surprise'

take only:

'/home/auto/'

Note that '/home/auto/gift/surprise' may vary, i.e., instead of having 4 directory levels, it may go to 6 or 8, yet I'm only interested in the first 2 folders.

Here's what I've tried so far, without success:

$ pwd
'/home/auto/gift/surprise' 
$ pwd | sed 's,^\(.*/\)\?\([^/]*\),\1,'
'/home/auto/gift/'
like image 806
user2482324 Avatar asked Dec 04 '25 07:12

user2482324


1 Answers

I think it is better to use cut for this:

$ echo "/home/auto/gift/surpris" | cut -d/ -f1-3
/home/auto
$ echo "/home/auto/gift/surpris/bla/bla" | cut -d/ -f1-3
/home/auto

Note that cut -d/ -f1-3 means: strip the string based on the delimiter /, then print from the 1st to the 3rd parts.

Or also awk:

$ echo "/home/auto/gift/surpris" | awk -F/ 'OFS="/" {print $1,$2,$3}'
/home/auto
$ echo "/home/auto/gift/surpris/bla/bla" | awk -F/ 'OFS="/" {print $1,$2,$3}'
/home/auto
like image 128
fedorqui 'SO stop harming' Avatar answered Dec 07 '25 00:12

fedorqui 'SO stop harming'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!