Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
add comment

3 Answers

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
do
  case "$line" in 
    *pattern* )
       line="${line//word/replace}"
  esac
  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:
        line=line.replace("pattern","replace")
    print line
share|improve this answer
add comment

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
add comment

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
add comment

Your Answer

 
discard

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.