bashawksed

How do I replace a character and add another one in front of a line one line below of it?


My goal is to overwrite the / character with a - at the end of a particular line and then insert a - at the front of that line and also at the front of the line one line below it. The test I've done is using sed as below:

$ cat input | sed -E 'N;s/^(- )?(.*\n)\//- \2-/;P;D'
$ cat input | sed 'N; \#\n/# { s//\n-/; s/^/- / }; P;D'
$ cat input | sed -E 'N;s|([^\n]*\n)/|- \1-|;P;D'
$ cat input | sed -Ez 's|([^\n]*\n)/|- \1-|g'

My input:

1
00:00:00,000 --> 00:00:00,000
<b><font color="#ffffff">Lorem Ipsum</font></b>

2
00:00:00,000 --> 00:00:00,000
Lorem ipsum dolor sit/
amet, consectetur adipiscing elit.

3
00:00:00,000 --> 00:00:00,000
Ut sed gravida nisi.

4
00:00:00,000 --> 00:00:00,000
Nunc sit amet ultrices urna,/
non efficitur neque. 

5
00:00:00,000 --> 00:00:00,000
<b><font color="#ffffff">Cras aliquam tristique dui, viverra laoreet diam hendrerit ac.</font></b>

My expected:

00:00:00,000 --> 00:00:00,000
<b><font color="#ffffff">Lorem Ipsum</font></b>

2
00:00:00,000 --> 00:00:00,000
- Lorem ipsum dolor sit
- amet, consectetur adipiscing elit.

3
00:00:00,000 --> 00:00:00,000
Ut sed gravida nisi.

4
00:00:00,000 --> 00:00:00,000
- Nunc sit amet ultrices urna,
- non efficitur neque. 

5
00:00:00,000 --> 00:00:00,000
<b><font color="#ffffff">Cras aliquam tristique dui, viverra laoreet diam hendrerit ac.</font></b>

Solution

  • With GNU sed:

    sed 's|/$||; T end; s/^/- /; n; s/^/- /; :end' file
    

    s|/$||; T end: search for trailing / and replace with nothing. I switched here from s/// to s|||. If there was no successful substitution then jump to label end.

    s/^/- /; n; s/^/- /;: Add leading - to pattern space. Read next line in pattern space and add leading - in pattern space.

    See: man sed