Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have one file contains data as follows...


How can I get the output that prints till 3rd occurrence of "/" in each line?

share|improve this question

migrated from stackoverflow.com Dec 9 '12 at 16:22

This question came from our site for professional and enthusiast programmers.

Anything that you have tried ? – GajananH Dec 7 '12 at 8:31
If your input is representative, it would probably be better to instead print everything up to the first ?, and awk '{print $1}' FS=? works nicely. – William Pursell Dec 7 '12 at 16:38
up vote 2 down vote accepted
awk -F/ 'BEGIN{OFS="/";}{print $1,$2,$3}' your_file
share|improve this answer
Thank you sarathi. – Lingaraj Dec 7 '12 at 10:02

It's as simple as this - separated by '/', cut fields 1-4:

cut -d'/' -f1-4


$ echo /foo/bar/baz/extra | cut -d'/' -f1-4
share|improve this answer
sed 's_\(/.*/.*\)/.*_\1_' your-file.txt

This is an example:

>sed 's_\(/.*/.*\)/.*_\1_' your-file.txt
share|improve this answer

cut's better, but with sed:

sed 's|/|\n|3;P;d'

You might need a literal newline with some seds, though.

share|improve this answer

With perl:

$ perl -F'/' -anle 'BEGIN{$,="/"} print @{[@F[0..2]]}' file
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.