How to find and replace string without use command Sed?
The classic alternative for single letter substitutions is the tr
command which should be available on just about any system:
$ echo "foobar" | tr a b
foobbr
tr
is better than sed
for this actually since using sed
(let alone perl
or awk
) for single letter substitutions is like using a sledge hammer to kill a fly.
grep
is not designed for this, it does not modify its input, it only searches through it.
Alternatively, you can use the substitution capabilities of some shells. Here using ksh
, zsh
or bash
syntax:
$ foo="foobar"
$ echo "${foo//a/b}"
foobbr
We could give you more specific answers if you explained exactly what problem you are trying to solve.
Yes there are a variety of ways to do this. You can use awk
, perl
, or bash
to do these activities as well. In general though sed
is probably the most apropos tool for doing these types of tasks.
Examples
Say I have this sample data, in a file data.txt
:
foo bar 12,300.50
foo bar 2,300.50
abc xyz 1,22,300.50
awk
$ awk '{gsub("foo", "foofoofoo", $0); print}' data.txt
foofoofoo bar 12,300.50
foofoofoo bar 2,300.50
abc xyz 1,22,300.50
Perl
$ perl -pe "s/foo/foofoofoo/g" data.txt
foofoofoo bar 12,300.50
foofoofoo bar 2,300.50
abc xyz 1,22,300.50
Inline editing
The above examples can directly modify the files too. The Perl example is trivial. Simply add the -i
switch.
$ perl -pie "s/foo/foofoofoo/g" data.txt
For awk
it's a little less direct but just as effective:
$ { rm data.txt && awk '{gsub("foo", "foofoofoo", $0); print}' > data.txt; } < data.txt
This method creates a sub-shell with the braces '{ ... }` where the file is redirected into it via this:
$ { ... } < data.txt
Once the file has been redirected into the sub-shell, it's deleted and then awk
is run against the contents of the file that was read into the sub-shells STDIN. This content is then processed by awk
and written back out to the same file name that we just deleted, effectively replacing it.
You can use the POSIX tool ex
:
ex a.txt <<eof
%s/Sunday/Monday/g
xit
eof
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/ex.html