Aleksandr Makov Aleksandr Makov - 25 days ago 6
Bash Question

bash: how can I read text in file into string, modify it and save it another file?

I have a file (imaginary):

test() {
echo ${%%NUMBER%%}
}


I need:


  1. Read it into string variable

  2. Replace
    %%NUMBER%%
    with number

  3. Save it to another file, maintaining the multi-line architecture.



How I do it:

#!/bin/bash

# Full path of this script
FILE=`readlink -f "${BASH_SOURCE[0]}"`

# This directory path
DIR=`dirname "${FILE}"`

repl() {
STRING=$(cat $DIR/skel.txt)
STRING=$(echo $STRING | sed "s/%%NUMBER%%/$1/")
echo $STRING
}

# try it
repl 50 > ./out.sh

# tried as well:
# repl 50 | tee ./out.sh
# echo "$(repl 50)" > ./out.sh
# STRING=$(echo -e $STRING | sed "s/%%NUMBER%%/$1/")


But I always get everything in one line in
out.sh
file. Need it to stay multiline, as in source.

Thanks.

Answer

Try this:

repl() {
    sed "s/%%NUMBER%%/$1/" "$DIR/skel.txt"
}

This is far more efficient, and won't eat your precious newlines.