This question already has an answer here:

If I have the text:

aaaaaaaaa
#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 #... there is a way to remove # using sed? Thanks in advance!

marked as duplicate by don_crissti, Romeo Ninov, user88036, jimmij, steve Oct 19 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.

up vote 5 down vote accepted

You can use perl:

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

Explanation:

  • -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 at 10:46
  • I tried with the non-greedy quantifier, but doesn't work. Good idea though with the &&. – RoVo Oct 17 at 10:48
  • That's a very common source of bugs, assuming the RE matches and $1 has s value – glenn jackman Oct 17 at 10:52
  • what do you mean with RE? could you make an example? Thanks to all of you! – tamarindoz Oct 17 at 12:37
  • RE = regular expression – RoVo Oct 17 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;}'

Output:

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 at 12:51

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