0

So, I want to read file from stdin, delete all '/' in line that contain exactly 3 '/', and write the output to stdout. So a file contain:

/a1/b/c
/a/b2
///
/a

will have output:

a1bc
/a/b2

/a

I am thinking something like this:

sed -r 's/\/[^\/]*\/[^\/]*\/.*/"I not sure what do I need to put in here"/g'

however, I am not really sure what do I need to put in the replace session.

2
  • Hello and Welcome to Programmers. Implementation specific questions are off-topic here. This question is on-topic for Stack Overflow but it appears you've already posted it there. Please don't crosspost. Have a pleasant day. Commented Mar 20, 2013 at 5:09
  • You should have a sample line such as /opt/hal/9000/monitor with 4 or more slashes in it; it should also be left unchanged. Commented Mar 20, 2013 at 6:31

3 Answers 3

2

A sed solution:

sed '/.*\/.*\/.*\//{s#/##g}' file

If Perl is ok for you:

perl -F/ -ape '$_=@F>3?join"",@F:join "/",@F;' file
Sign up to request clarification or add additional context in comments.

3 Comments

what is "{s#/##g}" mean? don't you think, if I replace it with nothing, it will delete the whole line instead of deleting only the '/'
Instead of using /, i used # as limitor. It will not delete the whole line, you can definitely test it against a sample file..
That regex will work on lines with three or more slashes, not just those with strictly three slashes.
0
sed -e '/^[^\/]*\/[^\/]*\/[^\/]*\/[^\/]*$/ s%/%%g'

The gruesome pattern looks for start of line, a sequence of zero or more non-slashes followed by a slash, more non-slashes and a second slash, more non-slashes and a third slash, more non-slashes and the end of line. On any line that matches that, substitute the slashes by nothing globally.

There are other ways to write the regex, but they aren't substantially clearer. This will work in pretty much any version of sed. So will this:

sed -e '/^\([^\/]*\/\)\{3\}[^\/]*$/ s%/%%g'

It looks for start of line, 3 units of (zero or more non-slashes followed by a slash), zero or more non-slashes and end of line.

If your sed has extended regular expressions (GNU sed, for example), then you can gain some notational convenience.

sed -r -e '/^([^\/]*\/){3}[^\/]*$/ s%/%%g'

sed -r -e 's%^([^/]*)/([^/]*)/([^/]*)/([^/]*)$%\1\2\3\4%'

The latter captures the four sets of 'zero or more non-slashes' and pastes them together to make the replacement. You could write that with the non-extended regular expressions, but it would be even more laden with backslashes than before.

Comments

-1

This is much simpler in awk:

awk -F/ 'NF==4 { gsub("/","") } {print}' tmp.txt

1 Comment

A comment to the answer by Guru indicates that the program must be sed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.