This question already has an answer here:

If I have the text:

#some info
other rows
end row#
another info

How could I extract only the text between the characters # obtaining only:

some info
other rows
end row

I was trying with sed in this way:

echo -e "aaaaaaaaa\n#some info\nother rows\nend row#\nanother info" |
sed -n -e '/\#/,/\#/p'

but it gives me also the character #. Is there a way to remove # using sed?

marked as duplicate by don_crissti, Romeo Ninov, user88036, jimmij, steve Oct 19 '18 at 9:47

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


You can use perl:

echo -e "aaaaaaaaa\n#some info\nother rows\nend row#\nanother info" |\
perl -0777 -ne '/#([^#]*)#/ && print $1,"\n"; '


  • -0777 slurp the whole file as one line (enables multiline matching)
  • /#([^#]*)#/ match non-# characters [^#] between too # and with the brackets add it as first matching group.
  • && print $1,"\n" if found, print first matching group and a final newline.
  • You could also use a non-greedy quantifier /#(.*?)#/ and you should probably use && instead of ; to separate the match and the print -- that will prevent a single newline from being printed if the match is not found. – glenn jackman Oct 17 '18 at 10:46
  • I tried with the non-greedy quantifier, but doesn't work. Good idea though with the &&. – RoVo Oct 17 '18 at 10:48
  • That's a very common source of bugs, assuming the RE matches and $1 has s value – glenn jackman Oct 17 '18 at 10:52
  • what do you mean with RE? could you make an example? Thanks to all of you! – tamarindoz Oct 17 '18 at 12:37
  • RE = regular expression – RoVo Oct 17 '18 at 12:40

Slight adaption to your sed one liner:

echo -e "aaaaaaaaa\n#some info\nother rows\nend row#\nanother info" |
sed -n '/^#/,/#$/ {s/#//;p;}'


some info
other rows
end row
  • thanks, but if the '#' is not the first or last character? In this case sed doesn't work !? – tamarindoz Oct 17 '18 at 12:51

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