Skip to content

Commit 0081dde

Browse files
committed
Fix backrefs in lineinfile or line mode
1 parent 3470e36 commit 0081dde

File tree

2 files changed

+46
-3
lines changed

2 files changed

+46
-3
lines changed

main.go

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,14 @@ func applyChangesetsToFile(fileitem fileitem, changesets []changeset) (string, b
103103
if opts.ModeIsLineInFile {
104104
for _, changeset := range changesets {
105105
if !changeset.MatchFound {
106-
buffer.WriteString(changeset.Replace + "\n")
106+
line = changeset.Replace + "\n"
107+
108+
// remove backrefs (no match)
109+
if opts.RegexBackref {
110+
line = regexp.MustCompile("\\$[0-9]+").ReplaceAllLiteralString(line, "")
111+
}
112+
113+
buffer.WriteString(line)
107114
writeBufferToFile = true
108115
}
109116
}
@@ -165,8 +172,16 @@ func applyChangesetsToLine(line string, changesets []changeset) (string, bool, b
165172
if searchMatch(line, changeset) {
166173
// --mode=line or --mode=lineinfile
167174
if opts.ModeIsReplaceLine || opts.ModeIsLineInFile {
168-
// replace whole line with replace term
169-
line = changeset.Replace
175+
if opts.RegexBackref {
176+
// get match
177+
line = string(changeset.Search.Find([]byte(line)))
178+
179+
// replace regex backrefs in match
180+
line = changeset.Search.ReplaceAllString(line, changeset.Replace)
181+
} else {
182+
// replace whole line with replace term
183+
line = changeset.Replace
184+
}
170185
} else {
171186
// replace only term inside line
172187
line = replaceText(line, changeset)

tests/main.test

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,34 @@ Testing replace mode with regex:
141141
this is the second line
142142
this is the third ___bar line
143143
this is the last line
144+
$ goreplace --regex --regex-backrefs -s 'not-existing-line' -r '___$1' test.txt
145+
$ cat test.txt
146+
this is a testline
147+
this is the second line
148+
this is the third ___bar line
149+
this is the last line
150+
151+
Testing lineinfile mode with regex:
152+
153+
$ cat > test.txt <<EOF
154+
> this is a testline
155+
> this is the second line
156+
> this is the third foobar line
157+
> this is the last line
158+
> EOF
159+
$ goreplace --mode=lineinfile --regex --regex-backrefs -s 'f[o]+(b[a]*r)' -r '___$1' test.txt
160+
$ cat test.txt
161+
this is a testline
162+
this is the second line
163+
___bar
164+
this is the last line
165+
$ goreplace --mode=lineinfile --regex --regex-backrefs -s 'not-existing-line' -r '___$1' test.txt
166+
$ cat test.txt
167+
this is a testline
168+
this is the second line
169+
___bar
170+
this is the last line
171+
___
144172

145173
Testing replace mode with regex and case-insensitive:
146174

0 commit comments

Comments
 (0)