How to grep repeated string on the same line?

I have this a file.txt with one line, whose content is

/app/jdk/java/bin/java -server -Xms3g -Xmx3g -XX:MaxPermSize=256m -Dweblogic.Name=O2pPod8_mapp_msrv1_1 -Djava.security.policy=/app/Oracle/Middleware/Oracle_Home/wlserver/server/lib/weblogic.policy -Djava.security.egd=file:/dev/./urandom -Dweblogic.ProductionModeEnabled=true -Dweblogic.system.BootIdentityFile=/app/Oracle/Middleware/Oracle_Home/user_projects/domains/O2pPod8_domain/servers/O2pPod8_mapp_msrv1_1/data/nodemanager/boot.properties -Dweblogic.nodemanager.ServiceEnabled=true -Dweblogic.nmservice.RotationEnabled=true -Dweblogic.security.SSL.ignoreHostnameVerification=false -Dweblogic.ReverseDNSAllowed=false -Xms8192m -Xmx8192m -XX:MaxPermSize=2048m -XX:NewSize=1300m -XX:MaxNewSize=1300m -XX:SurvivorRatio=4 -XX:TargetSurvivorRatio=90 -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled

and when I do

cat file.txt | grep -io "Xms.*" | awk '{FS" ";  print $1} ' | cut -d  "s" -f2

output:

3g

why is grep not reading the second occurrence, i.e. I expect 3g and 8192m .
Infact, how do I print only 8192m in this case?

If you want to print second occurrence try like this

$ awk -F"Xms" ' { sub(" .*","",$3); print $3 } ' file.txt
8192m
1 Like

When you have one line of input and you use grep to throw away the first part of the line and awk to throw away everything after the first <space> in what was left, you're not going to get much but the first value you were looking for.

Getting rid of the unneeded cat , grep , and cut and using awk to do all of what they were doing to get the results you want, you could try something more like:

awk '
{	for(i = NF; i > 0; i--)
		if($i ~ /^-Xms/) {
			print substr($i, 5)
			exit
		}
}' file.txt

If you really need a case insensitive search for Xms (which isn't needed with your input sample), you could change the start of the if statement to:

		if($i ~ /^-[Xx][Mm][Ss]/) {
2 Likes

A little variation of your own initial attempt:

$ grep -io "Xms[^ ]*" file.txt | cut -d  "s" -f2
3g
8192m
1 Like