I have a text file with ./.
and need to replace it with 0|0
.
The file is too big to open in Gedit and do it by hand.
Can I do it using sed
?
Yes. In this case it's useful to choose a different delimiter like _
, this way you don't have to escape the slash:
sed 's_\./\._0|0_'
Example:
$ cat test
./.
$ sed 's_\./\._0|0_' test
0|0
Add
-i
to change the file in place rather than print the output to stdout,-i.b
to do so and save a backup with .b
as an extension andg
to the end of the expression to change multiple occurences per line rather than just the first one (→ 's_\./\._0|0_g'
).s/A/B/
– replace A
by B
, the same as s_A_B_
, ssAsBs
or whatever you can imagine:
Any character other than backslash or newline can be used instead of a slash to delimit the BRE and the replacement. [source]
s/A/B/g
– replace A
by B
and do it g
lobally, so don't stop doing it after the first finding (per line!)
\./\.
– the literal string ./.
, a dot needs to be escaped with a backslash because they are part of basic regular expressions and else would take any character, matching a/a
, a/b
, ///
and so on0|0
– the literal string 0|0
Yes, you can do that with sed.
You need to escape .
and /
with a \
.
sed -i.bak 's/\.\/\./0|0/g' file
-i.bak
will make sed edit the file in place but creates a backup file with .bak extension.
The g
at the end means "global" --> Replaces all occurencies.
Even though you asked for sed
command to fulfill your requirement, you can also give a try to ex
command.
ex -sc '%s/\.\/\./0|0/g|x' file
%
select all lines
s
for substitute
g
replace all instances globally
x
write if changes made and exit
Example:-
$cp file file.bak
$cat file
./.
$ex -sc '%s/\.\/\./0|0/g|x' file
$cat file
0|0