Replacing string in file Unix
26,630
Solution 1
Use sed
to do a global substitution on file1.txt
and redirect the output to file2.txt
:
sed 's/apple-pie/apple_pie/g' file1.txt > file2.txt
Solution 2
sed
has better performance than awk
but both will work for this search and replace. Reference
If you put the commands in a script (e.g., ksh, sh) then here is the syntax:
awk '{gsub(/apple-pie/,"apple_pie");print}' "file1.txt" > "file2.txt"
sed -e 's/apple-pie/apple_pie/g' "file1.txt" > "file2.txt"
Author by
Mika H.
Updated on July 27, 2022Comments
-
Mika H. almost 2 years
I have a text file
file1.txt
on Unix. I'd like to produce another filefile2.txt
, in which I replace all occurrences ofapple-pie
withapple_pie
. What command can I use?