Home > OS >  How to delete all other characters except match case using Regex
How to delete all other characters except match case using Regex

Time:09-26

arn:aws:iam::aws:policy/AmazonEC2FullAccess
arn:aws:iam::aws:policy/IAMFullAccess
arn:aws:iam::s:policy/CloudWatchAgentServerPolicy
arn:aws:iam::aws:policy/AdministratorAccess
arn:aws:iam::aws:policy/aws-service-role/AWSSupportServiceRolePolicy
arn:aws:iam::aws:policy/aws-service-role/AWSTrustedAdvisorServiceRolePolicy
arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
arn:aws:iam::aws:policy/aws-service-role/AmazonElasticFileSystemServiceRolePolicy
arn:aws:iam::aws:policy/IAMAccessAnalyzerFullAccess
arn:aws:iam::aws:policy/aws-service-role/AWSBackupServiceLinkedRolePolicyForBackup

Here i need only the policy names which is at the end.

I need only the letters after /

this is the regex am using (?<=/).*

the output of this regex is this

  1. arn:aws:iam::aws:policy/AdministratorAccess

  2. arn:aws:iam::aws:policy/aws-service-role/AWSSupportServiceRolePolicy

As you can see in 1) it is greping correctly, but in 2) i need the letters after the last occurrence of /

and i need to delete everything except the match case.

Kindly someone drop your suggestions to achieve this.

Note: am aware that i can get the aws policy names using boto3, but am curious about the above usecase.

CodePudding user response:

You can just use grep with regexp and write result in another file. the remove original, if you want. Something like

grep -Eao '\(?<=/).*' 'logs.log' >result.log

CodePudding user response:

You can use the lookbehind assertion, and then match any char except a / or newline till the end of the string [^/\r\n] $

(?<=/)[^/\r\n] $

See a regex demo

If you use PCRE, you can also make use of \K to forget what is matched so far.

.*\/\K[^/\r\n] $

See another regex demo.

  • Related