How would i replace a string in a file such that the string to be replaced is always succeeded by 开发者_如何学编程some string.
eg: If i want to replace ABC with 123 as below,
INPUT
ABC
ABCXYZ
ABCDHD
ABC
CDE
OUTPUT
ABC
123XYZ
123DHD
ABC
CDE
i tried using sed but with no success.
Without capture using look-ahead:
s/ABC(?=\S)/123/;
sed -i 's/ABC\(.+\)$/123\1/g' myFile.txt
ABC
, match the literal ABC!
\(.+\)
match at least 1 other character capture it in group 1
123\1
replace the hole thing with 123 followed by what is captured in group 1
perl -pi.bak -e 's/^ABC(.+)$/123$1/g' file.txt
This will however replace whitespace too. If you do not want that, instead of .+
you can use \S+
.
The -i.bak
option will save a backup of file.txt
in file.txt.bak
, in case you bungled the replace.
this one worked for me:
$ sed -r s/ABC\(.+\)/123\\1/g <file>
ABC
123XYZ
123DHD
ABC
CDE
Surprised that no-one has used \B
.
#!/usr/bin/perl
use strict;
use warnings;
while (<DATA>) {
s/ABC\B/123/;
print;
}
__DATA__
ABC
ABCXYZ
ABCDHD
ABC
CDE
精彩评论