Home > Software design >  Sed print the items in square brackets that's after the occurence of a text
Sed print the items in square brackets that's after the occurence of a text

Time:11-03

I have the following Scenarios:

  • Scenario 1
foo_bar = ["123", "456", "789"]
  • Scenario 2
foo_bar = [
    "123", 
    "456", 
    "789"
]
  • Scenario 3
variable "foo_bar" {
  type    = list(string)
  default = ["123", "456", "789"]
}

So i'm trying to figure out how I can print with sed the items inside the brackets that are under foo_bar accounting scenario 2 which is a multiline

so the resulting matches here would be

Scenario 1

"123", "456", "789"

Scenario 2

 "123", 
 "456", 
 "789"

Scenario 3

"123", "456", "789"

In the case of

not_foo_bar = [
    "123", 
    "456", 
    "789"
]

This should not match, only match foo_bar

This is what I've tried so far

sed -e '1,/foo_bar/d' -e '/]/,$d' test.tf

And this

sed -n 's/.*\foo_bar\(.*\)\].*/\1/p' test.tf

CodePudding user response:

This is a mouthful, but it’s POSIX sed and works.

sed -Ene \
'# scenario 1
s/(([^[:alnum:]_]|^)foo_bar[^[:alnum:]_][[:space:]]*=[[:space:]]*\[)([^]] )(\]$)/\3/p

# scenario 2 and 3
 /([^[:alnum:]_]|^)foo_bar[^[:alnum:]_][[:space:]]*=?[[:space:]]*[[{][[:space:]]*$/,/^[]}]$/ {
    //!p
    s/(([^[:alnum:]_]|^)default[^[:alnum:]_][[:space:]]*=[[:space:]]*\[)([^]] )(\]$)/\3/p
}' |

# filter out unwanted lines from scenario 3 ("type =")
sed -n '/^[[:space:]]*"/p'

I couldn’t quite get it all in a single sed.

The first and last lines of the first sed are the same command (using default instead of foobar).

edit: in case it confuses someone, I left in that last [[:space:]]*, in the second really long regex, by mistake. I won’t edit it, but it’s not vital, nor consistent - I didn’t allow for any trailing whitespace in line ends in other patterns.

CodePudding user response:

This might work for you (GNU sed):

sed -En '/foo_bar/{:a;/.*\[([^]]*)\].*/!{N;ba};s//\1/p}' file

Turn off implicit printing and on extended regexp -nE.

Pattern match on foo_bar, then gather up line(s) between the next [ and ] and print the result.

  • Related