0

My document has the following aspect:

Text1
\begin{code}
code1
\end{code}
Text2
\begin{code}
  -- comment1
  code1A
\end{code}
Text3

\begin{code}
  -- comment2
  code1B
\end{code}
Text4

\begin{code}
codeB
\end{code}
Text 5

The output that I'm looking for is something like this:

code1

  -- comment1
  code1A

  -- comment2
  code1B

codeB
2
1

Note: An edit to the question has since made this solution obsolete.


Since you simply want to filter specific lines to the output, grep can do the job.

$ grep -v -e "T[0-9]" -e '^\\begin{code}$' -e '^\\end{code}$' file.txt
code1
  -- comment1
  code1A
  -- comment2
  code1B
codeB
1
  • It's not just T1 or T2, they are complete text including spaces, newlines... normal text. Nov 14 '18 at 16:04
1

Posting a desired output without specifying the rules / logics to apply for it to be obtained doesn't really help solving your problem. Someone could just echo / print the output without relation to the input. Assuming you want the lines between \begin{code} and \end{code} excluding either, try

sed -n '/\\begin/,/\\end/ {/{code}/!p}' file
code1
  -- comment1
  code1A
  -- comment2
  code1B
codeB

If you need the empty lines, append /^ *$/p to the sed script.

EDIT: Like so:

$ sed -n '/\\begin/,/\\end/ {/{code}/!p}; /^ *$/p' file
code1
  -- comment1
  code1A

  -- comment2
  code1B

codeB
6
  • Yes, I need the empty lines, how would it be, I tried "append ...", it doesn't work. Nov 14 '18 at 17:42
  • It does. I tested. WHAT did you append? In WHICH WAY doesn't it work?
    – RudiC
    Nov 14 '18 at 17:44
  • sed -n '/\\begin/,/\\end/ {/{code}/!/^ *$/p}' $< > $@. Nov 14 '18 at 17:46
  • See my edited answer.
    – RudiC
    Nov 14 '18 at 17:56
  • ``$ sed -n '/\\begin/,/\\end/ {/{code}/!p}; /^ *p' file``` I got this sed: 1: "/\\begin/,/\\end/ {/{co ...": extra characters at the end of p command Nov 14 '18 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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