How to extract multiple strings from a multiple lines text file with these rules? The search strings are "String server", " pac " and "String method". They may or may not appear only once within the enclosing "{}". After the search strings are matched, extract their values enclosed within "" without "()". The value of either search string "String server" or " pac " appear only once - no duplication. Its value will appear before the value of the search string "String method". e.g. sample text file in:
public AResponse retrieveA(ARequest req){
String server = "AAA";
String method = "retrieveA()";
log.info(method,
server,
req);
return res;
}
public BResponse retrieveB(BRequest req){
String method = "retrieveB()";
BBB pac = new BBB();
log.info(method,
pac,
req);
return res;
}
public CResponse retrieveC(CRequest req) {
String server = "CCC";
log.info(server,
req);
return res;
}
public DResponse retrieveD(DRequest req) {
String method = "retrieveD()";
log.info(method,req);
return res;
}
public EResponse retrieveE(ERequest req){
EEE pac = new EEE();
String method = "retrieveE()";
String server = "EEE";
log.info(method,
server,
pac,
req);
return res;
}
Expected output:
AAA retrieveA
BBB retrieveB
CCC
retrieveD
EEE retrieveE
I tried GNU Awk 5.0.1:
awk '{
if ($0 ~ /String method/ || ($0 ~ /String server/) )
{
str=$0;
sub("String", "", str);
sub(")", "", str);
sub("=", "", str);
gsub(/\(/, "", str);
gsub(/"/, "", str);
gsub(/;/, "", str);
if (str ~ /method/)
{
method = str;
gsub(/[[:blank:]]/, "", method);
gsub(/method/, "", method);
arr[i][1] = method
count++
} else if (str ~ /server/)
{
server = str;
gsub(/[[:blank:]]/, "", server);
gsub(/server/, "", server);
arr[i][0] = server
count++
}
}
if (count > 1 || $0 ~ /log./) {
count = 0
i++
}
}
END {
for (i in arr) {
printf "%s %s\n", arr[i][0], arr[i][1];
}
}' in
This
awksolution should work for you: