Sign up ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

I wish to write a shell script whereby I could read the file from command and edit the file without manual intervention (based on searching some text and replacing it with another).

I need not use any text editor for this....simply text-searching (like using grep) and then replacing it with some other text and saving the changes....

share|improve this question

4 Answers 4

up vote 4 down vote accepted

That is where sed comes in to play. A sed command has this format:

[pattern1][,pattern2][!] command [args]

It uses regexes so it can/will be a bit difficult. Some basic examples taken from the 2nd link below:

# substitute (find and replace) "foo" with "bar" on each line
sed 's/foo/bar/' # replaces only 1st instance in a line
sed 's/foo/bar/4' # replaces only 4th instance in a line
sed 's/foo/bar/g' # replaces ALL instances in a line
sed 's/\(.*\)foo\(.*foo\)/\1bar\2/' # replace the next-to-last case
sed 's/\(.*\)foo/\1bar/' # replace only the last case

# substitute "foo" with "bar" ONLY for lines which contain "baz"
sed '/baz/s/foo/bar/g'

# substitute "foo" with "bar" EXCEPT for lines which contain "baz"
sed '/baz/!s/foo/bar/g'

# change "scarlet" or "ruby" or "puce" to "red"
sed 's/scarlet/red/g;s/ruby/red/g;s/puce/red/g' # most seds
gsed 's/scarlet\|ruby\|puce/red/g' # GNU sed only

Some references

share|improve this answer
if you add -i meaning in place, I'll delete my answer – hbdgaf Jun 9 '12 at 6:19
Thanks, it was very helpful... – Rohit Bansal Jun 9 '12 at 6:21

You're looking for sed or awk. I find sed to be simpler and awk to be more powerful.

Here's an example from another question.
sed -i 's/gedit.desktop/yournew.desktop/g' /usr/share/applications/defaults.list
This means search in file /usr/share/applications/defaults.list
Find/grep gedit.desktop
Replace with yournew.desktop
Apply the changes in place -i

share|improve this answer

Depending on what you need to edit, if you're familiar with vi then ed may be useful.

share|improve this answer

If you want to edit a file, use a file editor, there are command based file editors that can be used from scripts, like ex or ed.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.