1

I have this file:

[default]
region = us-east-1
output = json
[profile automation]
region = us-east-1
output = json
[profile qa]
region = us-east-1
output = json

I need to extract only the profile names like so:

default
automation
qa

My sed so far:

gsed 's?\[[^\ ]*\ \([^\]]*\)?\1?' ~/.aws/config

As I'm testing, I can see that \([^\]]*\) matches only the first character after the space for example: the a in automation, the q in qa etc.. Why it only matches once? Do you have a better way of stripping the []? Thanks.

2

A backslash inside a bracketed expression is literal. You want [^]]. Your expression [^\]]* would match a non-backslash followed by an optional ].

$ sed -En 's/^\[(.* )?([^]]*)\]$/\2/p' file
default
automation
qa

This allows for optional words terminated by a space as the first substring inside [...], e.g. [group name]. The string after these optional words, up to the ], is captured in the second group.

The default printing of every line is turned off with -n and instead we print explicitly after each successful substitution.

We need -E since the ? modifier is an extended regular expression modifier.

Without -E you could use \{0,1\} in place of the ? (and change the capturing ( and ) into \( and \) respectively).

  • BREs have \{0,1\} as the equivalent of ERE ?, so you don't have to use that non-standard -E here. – Stéphane Chazelas Jan 30 at 9:35
  • Why don't I have to escape the ]? Why is it not treated as the end of the group? – Moshe Jan 30 at 9:52
  • 1
    @Moshe If ] occurs as the first character in the group, or as the first after ^, it will not end the group. – Kusalananda Jan 30 at 9:54
  • @Kusalananda this was the missing part! Thanks. – Moshe Jan 30 at 9:58
0

With GNU grep or compatible built with PCRE support:

grep -Po '^\h*\[\h*(\H+\h+)?\K.*[^]\h](?=\h*\]\s*$)'

We allow leading horizontal whitespace sometimes found for indentation and trailing whitespace, including vertical for the CR character generally found in MS Windows ini files.

On an input like:

[default]
[profile automation]
[profile a  b]
[profile  c d ]

It gives:

default
automation
a  b
c d

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.