Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm writing a shell script (bash) to fetch and build several bits of software. The script also writes several small config files and needs to alter a couple of pre-existing config files. What is the best way to find and substitute a few lines of a text file from a bash script?

This sounds like a job for sed, but I don't understand the syntax...

share|improve this question
up vote 4 down vote accepted

awk/sed/bash/Python/Perl/Ruby and most other tools/programming languages all can do manipulation of files. The "best" way is the way you are familiar and comfortable with. If you don't know anything about sed, look it up and learn about it. Otherwise, if you have a programming language you know, just do with it. Here's a bash script example

exec 6<"file"
while read -r line <&6
  case "$line" in 
    *pattern* )
  echo "$line"
done > "out"
exec 6<&-
mv out file

sed example

sed 's/word/replace/g' file

awk example

awk '{gsub(/word/,"replace")}1' file > t && mv t file

Python example (use 'with' for later versions)

for line in open("file"):
    if "pattern" in line:
    print line
share|improve this answer

Not an answer, but: http://catb.org/esr/writings/unix-koans/shell-tools.html

share|improve this answer
"When you are hungry, eat; when you are thirsty, drink; when you are tired, sleep." is sound advice but I have no food, water, or bed... – Frozenskys Sep 28 '10 at 10:30

sed s/@var@/$VALUE/g <config.in >config, but beware of stray slashes / in $VALUE -- you might need to escape them or use another separator char.

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.