Unix sed command to replace brackets in file
The issue with the command is the g
at the end. It will cause all double quotes to be substituted with <
on each line matching ^#include
. Notice how the StackOverflow question that you link to is concerned with replacing the <>
with ""
(which could be done using y/<>/""/
, or less efficiently using s/[<>]/"/g
, on the relevant lines), not the other way around like you want.
If you had used first s/"/</
(no g
) followed by s/"/>
(no g
here either), you would have been ok:
sed '/^#include/ { s/"/</; s/"/>/; }' file.c >file-new.c
The first substitution replaces the first double quote and the second substitution replaces the first one in the now modified string.
To correct the file (assuming you did an in-place edit), just replace the <
at the end of the line with >
:
sed '/^#include/ s/<$/>/' file.c >file-new.c
This matches <$
(an <
at the end of the line), and replaces it with >
.
Look at the resulting file-new.c
and then replace file.c
with it if it looks ok.
You need to replace two equal characters "
for two distinct characters <
and >
. Your command doesn't work because it replaces all occurrences of one character "
for one character only <
. So try this:
# capture the final word between double quotes
# and replace it for itself enclosed in brackets
$ sed '/^#include/s/"\([^"]*\)"/<\1>/' file
#include <stdlib.h>
#include <graph.h>