Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing string in file Unix

I have a text file file1.txt on Unix. I'd like to produce another file file2.txt, in which I replace all occurrences of apple-pie with apple_pie. What command can I use?

like image 717
Mika H. Avatar asked Dec 01 '12 21:12

Mika H.


2 Answers

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
like image 126
Chris Seymour Avatar answered Oct 03 '22 05:10

Chris Seymour


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"
like image 36
javaPlease42 Avatar answered Oct 03 '22 04:10

javaPlease42