John
John

Reputation: 309

Want to cut right before second trailing slash?

I wanted to cut the following rows right before second trailing slash.

Like

/home/john
/home/mathew
/home/alexander/public_html/path/to/file/1
/home/testuser/public_html/path/to/file/1
/home/hellouser/public_html/path/to/file/13

TO

/home/john
/home/mathew
/home/alexander
/home/testuser
/home/hellouser

How this can be done? using grep or cut or awk or sed? I am not sure.

Upvotes: 0

Views: 787

Answers (4)

Ed Morton
Ed Morton

Reputation: 204381

This is the job cut was invented to do:

$ cut -d'/' -f1-3 file 
/home/john
/home/mathew
/home/alexander
/home/testuser
/home/hellouser

There was a big clue in your question: "Want to cut..."

Upvotes: 3

user4453924
user4453924

Reputation:

awk -F/ -vOFS="/"  'NF=3' file

/home/john
/home/mathew
/home/alexander
/home/testuser
/home/hellouser

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174816

You could try the below awk commands.

awk  'BEGIN{FS=OFS="/"}{print $1,$2,$3}' file

BEGIN{FS=OFS="/"} at the BEGIN block, / was set as value of FS and OFS. comma on the print function prints the OFS value.

OR

awk -F/ '{print FS$2FS$3}' file

OR

$ awk -F/ '{print $1FS$2FS$3}' file
/home/john
/home/mathew
/home/alexander
/home/testuser
/home/hellouser

Upvotes: 3

Dragan
Dragan

Reputation: 455

You can use awk

awk -F/ '{print "/" $2 "/" $3}'

Upvotes: 0

Related Questions