I'm running ansible playbook task using shell command to extract data from file based on regex match and save it to another file.
I tried using awk and sed but not able to get the regex working.
awk '$NF == "-m.comment.*\""' iptable.txt" > file1.txt
sed 's/\/.*' iptable.txt > file2.txt
I need to save any content from -m comment till the double quotes. to file1.txt and remaining content to file2.txt. If the line doesnot have comment field, then it should be saved only to file2.txt.
-P INPUT ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p icmp -m state --state NEW -m comment --comment "Echo Request" -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m comment --comment "tcp" -j ACCEPT
Expected output: cat file1.txt
-m comment --comment "Echo Request"
-m comment --comment "tcp"
cat file2.txt
-P INPUT ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p icmp -m state --state NEW -j ACCEPT
-A INPUT -p tcp -m state --state NEW -j ACCEPT
I know regex is right as I tested with regex tester- proving that a regex works in some online tool ONLY proves that it works in that online tool. That does not mean it'll work in sed, awk or any other command line tool. There's just WAY too many regexp variants, tool variants, extensions, delimiters, options, etc. to think that you can test a regexp in foo and that means it'll work in bar. - Ed Morton