1

When detecting the line containing the pattern night, we need to detect its corresponding line containing the other pattern === which is just occurring at a higher line as shown below.

  • File content:

=== test1.log
boo
bar
game
=== file23.txt
night78
far
night
text
=== log3.c
aaa
limit
night3

  • Output:

    === file23.txt
    night78
    night
    === log3.c
    night3

2

You can do it with awk with something like this:

 awk '/===/ {SEC=$0;PRINTED=0} /night/ {if(!PRINTED) print SEC; print $0; PRINTED=1;}' <file>

which will look for the === line and store that, and note that it has not yet printed that one. Then if it finds the pattern night it will check if it has already printed the section header or not, print it if not, then print the current line and mark that it has already printed the section header.

  • when launching this command I'm getting below error. awk '/===/ {SEC=$0;PRINTED=0} /night/ {if(!PRINTED) print SEC; print $0; PRINTED=1;}' test.txt awk: syntax error near line 1 awk: bailing out near line 1 – ekassis May 8 '15 at 13:56
  • I'm using GNU's gawk is it possible you're using a different one? I have not tried this with, say, mawk – Eric Renouf May 8 '15 at 14:00
  • Thank you Eric! gawk worked properly! – ekassis May 8 '15 at 14:12
  • I'm not able to pass to the command a variable $pattern. Can you please assist? gawk "/===/ {SEC=$0;PRINTED=0} /$pattern/ {if(!PRINTED) print SEC; print $0; PRINTED=1;}" describe.txt – ekassis May 8 '15 at 14:41
  • Changing to double quotes will let you pass $pattern but then you have to escape all the other places where $ is used, like $0 will have to become \$0 and so forth – Eric Renouf May 8 '15 at 14:43
0

Tried this with the sed

sed -n '/===/{
h
d
}
/night/{
G
s/\(.*\)\n\(.*\)/\2\
\1/p
}' inputFile

This is not exactly what you wanted, but quite similar.

=== file23.txt
night78
=== file23.txt
night
=== log3.c
night3
  • /== hold current pattern in buffer
  • /night match all lines containing token night
  • G append current buffer to the current pattern space.
  • /s swap the position of current patten string and current buffer string.

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.