Using sed to extract a substring in curly braces

Currently, I got the line as below:

integration@ {Wed Nov 19 14:17:32 2014} branch: thebranch 

This is contained in the file, and I am parsing the line. However, I want the value between the brackets {Wed Nov 19 14:17:32 2014}

I have no experience with Sed, and to be honest, I find this a bit cryptic.

So far I have managed to use the following command, however the output is still a whole line.

What am I doing wrong?

 sed -e 's/[^/{]*"\([^/}]*\).*/\1/' 
+6
source share
4 answers

To get values ​​that were between { , }

 $ sed 's/^[^{]*{\([^{}]*\)}.*/\1/' file Wed Nov 19 14:17:32 2014 
+3
source

This is very easy to do with awk , without complicating the regex.

 awk -F"{|}" '{print $2}' file Wed Nov 19 14:17:32 2014 

It sets the field separator to { or } , then your data will be in the second field.

FS can be installed as follows:

 awk -F"[{}]" '{print $2}' file 

To see all fields:

 awk -F"{|}" '{print "field#1="$1"\nfield#2="$2"\nfield#3="$3}' file field# 1=integration@ field#2=Wed Nov 19 14:17:32 2014 field#3= branch: thebranch 
+4
source

It can work

 sed -e 's/[^{]*\({[^}]*}\).*/\1/g' 

Test

 $ echo " integration@ {Wed Nov 19 14:17:32 2014} branch: thebranch" | sed -e 's/[^{]*{\([^}]*\)}.*/\1/g' 

Wed Nov 19 14:17:32 2014

Regex

  • [^{]* Matches anything other than { , that is, integration@

  • ([^}]*) Capture group 1

    • \{ Corresponds to {

    • [^}]* matches anything other than } , i.e. Wed Nov 19 14:17:32 2014

    • \} matches }

  • .* matches the rest

+2
source

Just below the command will also get the data ...

 echo " integration@ {Wed Nov 19 14:17:32 2014} branch: thebranch" | sed 's/.*{\(.*\)}.*/\1/g' 
+1
source

Source: https://habr.com/ru/post/978500/


All Articles