5

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 #. Is there a way to remove # using sed?

SouravGhosh
  • 553
  • 5
  • 12
tamarindoz
  • 53
  • 1
  • 4

2 Answers2

5

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.
pLumo
  • 22,231
  • 2
  • 41
  • 66
  • 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 `&&`. – pLumo 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 – pLumo Oct 17 '18 at 12:40
  • "assuming the RE matches and $1 has s value" for example if its call inside an script where $1 is the argument of the script? do you mean this or ? thanksss! – tamarindoz Oct 17 '18 at 12:56
  • No, that is prevented by the single quotes. He means I should not do `do_something; do_something_dependent;` but rather `do_something && do_something_dependent;`. In this case `print $1` is dependent on the pattern match (`/#([^#]*)#/`). If you don't know what I am talking about, read [this](https://stackoverflow.com/questions/4510640/what-is-the-purpose-of-in-a-shell-command). – pLumo Oct 17 '18 at 13:01
5

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
agc
  • 7,045
  • 3
  • 23
  • 53
RudiC
  • 8,889
  • 2
  • 10
  • 22