Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove some character in the start and in the end using sed

Tags:

regex

grep

sed

awk

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 "]"

like image 583
Jatin Mehrotra Avatar asked Dec 08 '22 09:12

Jatin Mehrotra


1 Answers

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 value
  • p - 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).

like image 77
Wiktor Stribiżew Avatar answered Feb 24 '23 12:02

Wiktor Stribiżew