Issue
I wanted to search for multiple matches in a single line and output only the matched words using grep
alias host='echo -e "Connecting to host 10.10.11.120\n===================";ssh [email protected]'
alias host1='echo -e "Connecting to host 10.10.11.121\n===================";ssh [email protected]'
alias host2='echo -e "Connecting to host 10.10.11.122\n===================";ssh [email protected]'
alias host3='echo -e "Connecting to host 10.10.11.123\n===================";ssh [email protected]'
I want grep to output only the host name and IP address like
host 10.10.11.120
host1 10.10.11.121
host2 10.10.11.122
host3 10.10.11.123
Solution
With grep
and pcre
, required strings can be extracted
$ grep -oP 'alias \K[^=]+|@\K[0-9.]+' ip.txt
host
10.10.11.120
host1
10.10.11.121
host2
10.10.11.122
host3
10.10.11.123
However, each extracted string would be in separate line, so one can use other commands to join them, for ex:
$ grep -oP 'alias \K[^=]+|@\K[0-9.]+' ip.txt | paste - -
host 10.10.11.120
host1 10.10.11.121
host2 10.10.11.122
host3 10.10.11.123
Or, a single perl
command can also be used:
$ perl -pe 's/alias (host\d*).*@([\d.]+).*/$1 $2/' ip.txt
host 10.10.11.120
host1 10.10.11.121
host2 10.10.11.122
host3 10.10.11.123
Answered By - Sundeep