Saturday, February 5, 2022

[SOLVED] print the next word after matching either one of the pattern. next word could be space separated or equal sign

Issue

print the next word after matching either one of the pattern i.e "-l" or "--log-file=". next word could be space separated or equal sign "="

cat server.log
server_options='-l /tmp/server_log --log-level=1'

cat server1.log
server_options='--log-file=/tmp/server1_log --log-level=1'

expected output for the first example [only the very next word after finding pattern and not till end of line]:-

/tmp/server_log

expected output for the second example [only the very next word after finding pattern and not till end of line]:-

/tmp/server1_log

With the following it prints when "-l" is specifed

$ grep -Po '^[^#;].*(-l|--log-file) \K.*(?=.)' server.log
/tmp/server_log

but it doesn't work when "--log-file=" is specified

 $ grep -Po '^[^#;].*(-l|--log-file) \K.*(?=.)' server1.log

Note:- there can be multiple options for example "-a" "-f" along with -l or --log-file and can be in any position inside quotes


Solution

You can use:

grep -Po "^[^#;].*(-l |--log-file=)\K[^\s']+" server.log

Remember that -l is followed by a space but -log-file is followed by a =

This grep requires a gnu grep.



Answered By - anubhava
Answer Checked By - Senaida (WPSolving Volunteer)