sedbackreference

Sed expression to convert only certain lines starting with some example phrase


There's an example file with a regular text. In some places of the document there's a mix of the following lines:

| ![](/img/2016/12/020.jakis-tam-text1.png#medium) | ![](/img/2016/12/021.jakis-tam-text2.png#medium) | ![](/img/2016/12/022.jakis-tam-text3.png#medium) |
| ![](/img/2016/12/020.jakis-tam-text1.png#medium) | ![](/img/2016/12/021.jakis-tam-text2.png#medium) |

There's the following sed expression to convert the lines to the required form:

sed 's#\([^[]*.\)\([^\.]*.\([^\.]*\)[^)]*.\)#\1\3\2#g'

How to apply this sed expression to only those lines that start with | ![]( ?


Solution

  • Your pattern is not quite right: . when unescaped matches any char. Also, note you do not need to escape . chars inside bracket expressions.

    I suggest the following command:

    sed '/^|[[:space:]]!\[](/s#\(|[[:space:]]!\[\)\(]([^().]*\.\([^|.]*\)\.[^()]*)\)#\1\3\2#g'
    

    See online demo.

    Here, the POSIX BRE pattern matches

    The replacement is the concatenation of Group 1, 3 and 2.