-1

I'm writing a Bash script to convert Arch Linux packages into a format for a package manager I'm writing, and I have to convert some metadata files into file format .toml. Previously, I've been using sed, but I just need something I can implement into a Bash script. The conversion should look like shown below.

Input:

... other stuff ...
depends = "some-dependency"
depends = "another-dependency"
depends = "yet-another-dependency"

Output:

... other stuff already converted ...
depends = [ "some-dependency", "another-dependency", "yet-another-dependency" ]
  • With GNU awk: `awk 'BEGIN{FPAT="\"[^\"]*\""; RS=""; OFS=", "} {$1=$1; print "depends = [ " $0 " ]"}' file`? – Cyrus Feb 19 '23 at 00:28
  • It kinda works, but it puts all of the input fields in instead of only `depends` lines. I should've mentioned that the input has more than just `depends`. I will try to edit it, but I don't really know awk that well. – universeindex Feb 19 '23 at 00:39
  • 2
    Welcome, you say *"I've been using sed, but I just need something I can implement into a bash script"*. I'm not sure I understand, why can't you use `sed` inside a bash script? – schrodingerscatcuriosity Feb 19 '23 at 01:18
  • What's the "other stuff" that you do not mention? – Kusalananda Feb 21 '23 at 11:37
  • Regarding `should've mentioned that the input has more than just depends` - yes but, more importantly, you should have included lines with more than `depends` in the sample input/output you provided to demonstrate your requirements and for us to test a potential solution with. – Ed Morton Feb 21 '23 at 17:36

2 Answers2

1

Using awk:

awk -F' = ' '
    $1 == "depends" {
        printf "%s %s", (flag!=1 ? "depends = [" : ","), $2
        flag=1
        next
    }
    flag {
        print " ]"
        flag=0
    }
    { print }
    END {
        if (flag) print " ]"
    }
' file

Input:

... other stuff ...
depends = "some-dependency"
depends = "another-dependency"
depends = "yet-another-dependency"
... more stuff ...
depends = "next-dependency"
depends = "and-another-dependency"

Output:

... other stuff ...
depends = [ "some-dependency", "another-dependency", "yet-another-dependency" ]
... more stuff ...
depends = [ "next-dependency", "and-another-dependency" ]
Freddy
  • 25,172
  • 1
  • 21
  • 60
0

Excluding "...other stuff.." section from the input file, you can use this code:

$ awk -F"=" 'NR==1{printf $1 " = [" } {printf $2 ","};END{print""}' infile | sed 's/.$/\]/'

depends  = [ "some-dependency", "another-dependency", "yet-another-dependency"]
dhm
  • 362
  • 1
  • 6