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...

3 Answers 3


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

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

  • "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, 2010 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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .