Replace string which include \t \n in shell script

157 views Asked by At

The file foo.h is:

do {                                                              \
        if (a == b) {                                      \
            c = 1;                                         \
        }                                                         \
    \
} while (0)

In this, for last 2 lines the pattern will be

"\t\\\n} while (0)"

I want to replace this pattern with

"\t} while (0)".

I tried with

sed -i -- 's/\t\\\n} while (0)/\t} while (0)/g' "foo.h"

. But I am not getting as expected. I want final foo.h should be like this:

 do {                                                              \
        if (a == b) {                                      \
            c = 1;                                         \
        }                                                         \
} while (0)

We can't replace "\t\\\n" together? or any other utility for this?

2

There are 2 answers

0
anubhava On

You can use this gnu-sed command:

sed -i 'N;s/\t\\\n\(} while (0)\)/\1/' foo.h

cat foo.h

do {                                                              \
        if (a == b) {                                      \
            c = 1;                                         \
        }                                                         \
} while (0)
0
Markus Dutschke On

your problem was, that sed reads and substitutes linewise.

This can be circumvented as explained here, by Zsolt Botykai

Hence, the working command is:

sed -e ':a;N;$!ba;s/\t\\\n} while/} while/g' foo.h