Ask Your Question
2

How can you output a line that has a certain pattern, only if it is preceded by a different line that has a different pattern?

asked 2022-04-21 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-07-21 22:00:00 +0000

lakamha gravatar image

This can be achieved using the grep command with the -B option. The -B option allows you to specify the number of lines to display before the matched line.

For example, if you want to output a line that has the pattern "success" only if it is preceded by a line that has the pattern "login", you can use the following command:

grep -B 1 "success" file.txt | grep "login"

This command will search for the pattern "success" in the file.txt and display the line that matches, along with the line that precedes it (specified by the -B 1 option). The output is then piped to another grep command that searches for the pattern "login". This will ensure that the line with the pattern "success" is only displayed if it is immediately preceded by a line that has the pattern "login".

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-21 11:00:00 +0000

Seen: 13 times

Last updated: Jul 21 '22