Aleksandr Makov Aleksandr Makov - 1 year ago 74
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
    with number

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

How I do it:


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

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

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


Answer Source

Try this:

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

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