-1

I'm trying to parse the lines of an .aws/config or .aws/credentials file of a specific profile such as [default] or [prod].

File example

[default]
region = us-east-1
output = json

[nonprod]
region = us-east-1
output = json

[uat]
region = us-east-2
output = json

[prod]
region = us-east-1
output = json

Does anybody have a (aws, sed, grep, etc) script that searches for (and displays) the lines after e.g. [default] until the start of the next profile, or if searching for prod starting with [prod] until the end of the file?

Examples

searchawsconfig default
searchawsconfig prod
Bernie Lenz
  • 193
  • 4
  • 11
  • 1
    Does this answer your question? [How to grep for text in a file and display the paragraph that has the text?](https://unix.stackexchange.com/questions/82944/how-to-grep-for-text-in-a-file-and-display-the-paragraph-that-has-the-text) – Quasímodo Sep 17 '20 at 14:21
  • The paragraph approach is pretty neat, but I was wondering if there are any other solutions than blank separated paragraphs? e.g. maybe search for the profile name, start outputting the next line util there is a [ at the beginning of the line? – Bernie Lenz Sep 17 '20 at 18:16
  • What's a "profile" - is it a name in square brackets? – roaima Sep 20 '20 at 22:55
  • @roaima yes, aws calls those profiles – Bernie Lenz Sep 21 '20 at 12:24

3 Answers3

3

If the profiles are blank-separated, then you can use awk in paragraph mode ex.

$ awk -v RS= -v p='[uat]' '$1 == p' yourfile
[uat]
region = us-east-2
output = json
steeldriver
  • 78,509
  • 12
  • 109
  • 152
2

Perl in "paragraph mode":

$ perl -00 -ne 'print if /\[default\]/' file 
[default]
region = us-east-1
output = json

or

$ perl -00 -ne 'print if /\[prod\]/' file 
[prod]
region = us-east-1
output = json

You could make this into a shell function by adding these lines to your shell's initialization file (e.g ~/.bashrc):

searchawsconfig(){
    perl -00 -ne 'print if /\['"$1"'\]/' "$2" 
}

You can then do:

$ searchawsconfig prod file 
[prod]
region = us-east-1
output = json
terdon
  • 234,489
  • 66
  • 447
  • 667
1

abstract:

awk '$1==p' RS= p='[default]' ./tst

Using the paragraph mode to split the input file into records that are delimited with an "empty line" (two consecutive \n).

You can do regex matching with (escape [] as they are special in regex) (use ^ to mark the start of a line):

awk -vRS='' '/^\[default\]/' ./tst

Or you can do text matching (full first line) with:

awk -vRS='' '$1 == "[default]"' ./tst

Or (more flexible) use variables set in the command line:

awk '$1==p' RS= p='[default]' ./tst

Make sure to use some form of a path, like the relative path ./ to ensure that the file name is parsed as a filename even if it contains =.

Or, using environment variables:

RS='' SECTION='default'   \
    awk   'BEGIN{RS=ENVIRON["RS"]} $1=="[" ENVIRON["SECTION"] "]" ' \
        ./tst