Home > Back-end >  how to add begin of line with multilines with delimiter?
how to add begin of line with multilines with delimiter?

Time:04-23

I have a file like this:

Input:

---
a
b
c
d
---
a
b
c
d
---
a
b
c
d

And I would like to add same structure at each block delimited by --- like:

Output:

---
1: a
2: b
3: c
4: d
---
1: a
2: b
3: c
4: d
---
1: a
2: b
3: c
4: d

I try using sed like:

sed -i '1s/a: /\1/' 

and so on but it keeps adding to the first line.

Best regards.

CodePudding user response:

One awk idea:

awk '{ pfx=  count ": "        # set default prefix as incremented counter   ": "
       if ($0 ~ /^---/)        # if lines starts with "---" then ...
           pfx=count=""        # reset variables
       print pfx $0            # print prefix plus current line
     }' x

or as a one-liner (sans comments):

awk '{ pfx=  count ": "; if ($0 ~ /^---/) pfx=count=""; print pfx $0 }' x

This generates:

---
1: a
2: b
3: c
4: d
---
1: a
2: b
3: c
4: d
---
1: a
2: b
3: c
4: d
  •  Tags:  
  • bash
  • Related