4

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

4

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
1

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 '10 at 10:30
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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