My bash variable $line contains output of other command. Ip and username could be in different places inside one line :
10.20.0.11 01User3645 123213123213 http://amazon.com
af 10.20.0.12 http://amazon.com 02User4536
01User3645 123213123213 10.20.0.11 http://amazon.com
af 02User4536 http://amazon.com 10.20.0.12
01User0011 123213123213 http://amazon.com 10.20.0.11
I'm trying to sed or grep this variable with two patterns to get only ip address and username:
10.20.0.11 01User3645
10.20.0.12 02User4536
10.20.0.11 01User3645
10.20.0.12 02User4536
10.20.0.11 01User0011
With commands bellow it was possible to print desired result but with separated lines:
echo "$line" | grep -E -o '10\.[0-9] \.[0-9] \.[0-9] |[0-9] User[0-9] '
Output:
10.20.0.11
01User3645
10.20.0.12
02User4536
10.20.0.11
01User3645
The question here is how to combine output of ip-address and username in one line for each line in variable? Thanks!
CodePudding user response:
With bash
and two regex:
echo "$line" \
| while read -r line; do
[[ $line =~ 10\.[0-9] \.[0-9] \.[0-9] ]] && echo -n "${BASH_REMATCH[0]} ";
[[ $line =~ [0-9]{2}User[0-9]{4} ]] && echo "${BASH_REMATCH[0]}";
done
Output:
10.20.0.11 01User3645 10.20.0.12 02User4536 10.20.0.11 01User3645 10.20.0.12 02User4536 10.20.0.11 01User0011
CodePudding user response:
Here is an awk
solution for this task:
awk '
match($0, /10\.[0-9] \.[0-9] \.[0-9] /) {
printf "%s ", substr($0, RSTART, RLENGTH)
}
match($0, /[0-9] User[0-9] /) {
print substr($0, RSTART, RLENGTH)
}' <<< "$line"
10.20.0.11 01User3645
10.20.0.12 02User4536
10.20.0.11 01User3645
10.20.0.12 02User4536
10.20.0.11 01User0011