15

I know how to add new text to a file, but how can I edit it?

Example: adding hello_world = 1 to test.txt using the following command:

echo "hello_world = 1" >> test.txt

But how can I change 1 to 0 or something else?

Pandya
  • 34,843
  • 42
  • 126
  • 186
Marco98T
  • 367
  • 3
  • 6
  • 14
  • What is your mean by without open editor i.e. you don't want use also **useful CLI text editor like: `vi` or `nano`** as well as GUI like: `gedit` – Pandya Jul 02 '14 at 12:08
  • because I want to make a script for my android, I know android use linux kernel and has some linux command. And my script working perfectly – Marco98T Jul 05 '14 at 09:28

2 Answers2

35

Using sed:

sed -i 's/1/0/g' test.txt

In general:

sed -i 's/oldstring/newstring/g' filename

See man sed for more info.

Radu Rădeanu
  • 166,822
  • 48
  • 327
  • 400
  • for single substitution, you don't even need a global flag. – Avinash Raj Jul 02 '14 at 11:55
  • Downvote because answer is already exists [here](http://askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands). – c0rp Jul 02 '14 at 12:17
  • Why do you downvote the correct answer then, cOrp, and not the duplicate question? – foo Sep 03 '20 at 14:19
5

Through awk,

awk '{sub(/1/,"0")}1' infile > outfile

Example:

$ echo 'hello_world = 1' | awk '{sub(/1/,"0")}1'
hello_world = 0
Avinash Raj
  • 77,204
  • 56
  • 214
  • 254