Courier
Courier

Reputation: 940

Replacing only a part of strings that start with certain characters in bash

Am not quite familiar with bash coding. I have a cpp file

#include <lib1.h>
#include <ccLib1.h>
#include <anotherlib.h>
#include <ccToto.h>

How to make a script that would automatically replace <cc*.h> with "*.h"; replacing only those that start with cc?

I tried something like sed -i -e 's/cc*>/"/g' file.cpp

Upvotes: 0

Views: 157

Answers (3)

Cyrus
Cyrus

Reputation: 88999

With GNU sed:

sed '/^#include/{s/<cc\(.*\.h\)>/"\1"/;}' file

Output:

#include <lib1.h>
#include "Lib1.h"
#include <anotherlib.h>
#include "Toto.h"

See: The Stack Overflow Regular Expressions FAQ

Upvotes: 5

gzh
gzh

Reputation: 3616

sed 's/^#include\ \(<cc\|<\)\(.*\)\.h>/#include "\2\.h"/g' so_file.cpp

Upvotes: 0

Dilettant
Dilettant

Reputation: 3345

For complete solutions of the amended / updated question cf. the answer of @Cyrus on this page together with the comments for eventual portability tricks. It additionally

  1. anchors the stream edit expression on ^#include and
  2. transforms from <...> to "..."in the matching cases.

A simple context free solution without the later explicated transform to a different search path includes (from <ccHeader,h> to "Header.h")

$> sed  's/<cc\(..*\.h>\)/<\1/g' so_file.cpp

#include <lib1.h>
#include <Lib1.h>
#include <anotherlib.h>
#include <Toto.h>

sed does on my machines not like the notion of at least one any character via .+ so I simply give it ..* without discussing further ;-)

You will want at least a character for the basename of the header, so a cc.h would be left intact.

Upvotes: 0

Related Questions