On 2015-05-24 16:21, Meino.Cramer@gmx.de wrote:
> When replacing character/words in a text with vim, I can
> limit the search'n'replace-areaa with a visual selection
> and giving a \%V in the search pattern.
>
> I need to build a shell script, which does exactliy
> this: Replaceing character in a limited range of columns.
>
> Can I do this with sed somehow?
While not perfect and there are some odd edge-cases, you can try
sed ':a;s/^\(.\{29,39\}\)x/\1y/;ta' myfile.txt > output.txt
where 30=the left hand column minus 1 (the minimum number of
characters that can precede the match), 39=the right-hand column minus
the number of characters in the search term (len("x")=1) (the
maximum number of characters that can precede a valid match), and "y"
is the replacement. So for a three-character search term in columns
20-30, you'd use
sed ':a;s/^\(.\{19,27\}\)abc/\1xyz/;ta'
There are edge-cases where the pattern is not a fixed-width, or the
replacement isn't the same size as the pattern. Or where the
replacement contains the search term ("s/x/xx/"). There might be
others, but I encountered these when testing. In these degenerate
cases, it may be attempting to perform an infinite number of
replacements, so just ^C to kill it.
It breaks down as
:a a label to return to
s/ substitute, searching for:
^ assert the start of the line
\( capture the stuff preceding our search expression
.\{19,27\} 19-27 of any character has to precede the match
\) end of the capture group
abc the search expression
/ replace that with
\1 the stuff we captured
xyz our replacement
/
ta If we successfully performed a replacement, go
back to the "a" label and try to do it again.
If we didn't, proceed to the next line and
repeat the whole process again
to do more than that, you might need something more powerful like
Perl's look-behind/look-ahead assertions (I'm a Python guy, not a
Perl guy, so I can only take an uneducated stab at that if you need
it).
-tim
PS: there's a sed-users mailing list
http://groups.yahoo.com/group/sed-users/
in case you have more sed questions. Though sed posts on the vim
mailing list are more "TT" (Tangentially Topical) than completely OT.
--
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php
---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment