I am trying to extract word between "profile "
and "]"
.
my contents
[profile gateway]
[profile personal]
[profile DA]
[profile CX]
for this i have tried
less ~/.aws/config |grep "\[profile"|sed -E 's/\[profile(.)//'
which gives
gateway]
personal]
DA]
CX]
I know can add a pipe and us tr to delete last "]"
or even cut would do but can someone help me with above sed command with regex to remove last "]"
You can use sed
:
sed -n 's/.*\[profile *\([^][]*\).*/\1/p' ~/.aws/config
Details:
-n
- suppress default line output.*\[profile *\([^][]*\).*/
- find any text, [profile
, zero or more spaces, then capture into Group 1 any zero or more chars other than [
and ]
, and then match the rest of the text\1
- replace with Group 1 valuep
- print the result of the substitution.See an online demo:
s='[profile gateway]
[profile personal]
[profile DA]
[profile CX]'
sed -n 's/.*\[profile *\([^][]*\).*/\1/p' <<< "$s"
Output:
gateway
personal
DA
CX
With a GNU grep
grep -oP '(?<=\[profile )[^]]+' ~/.aws/config
The (?<=\[profile )[^]]+
regex matches a location that is immediately preceded with profile
string and then matches one or more chars other than ]
. -o
option makes grep
extract the matches only and P
enables the PCRE regex syntax.
With awk
You may also use awk
:
awk '/^\[profile .*]$/{print substr($2, 0, length($2)-1)}' ~/.aws/config
It will find all lines that start with [profile
, and oputput the second field without the last char (that is a ]
char that will get omitted).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With