Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace certain token with the content of a file (using a bash-script)

I have a file containing some text and the words INSERT_HERE1 and INSERT_HERE2. I'd like to replace these words with the content of file1.txt and file2.txt respectively.

I suspect sed or awk could pull it off but I've basically never used them.

like image 551
aioobe Avatar asked Dec 07 '10 16:12

aioobe


People also ask

How do I replace a string in a bash script?

The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.

What does $@ do in bash script?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


2 Answers

Sed does have a built-in read file command. The commands you want would look something like this:

$ sed -e '/INSERT_HERE1/ {
r FILE1
d }' -e '/INSERT_HERE2/ {
r FILE2
d }' < file

This would output

foo
this is file1
bar
this is file2
baz

The r command reads the file, and the d command deletes the line with the INSERT_HERE tags. You need to use the curly braces since sed commands and multi-line input since sed commands have to start on their own line, and depending on your shell, you may need \ at the end of the lines to avoid premature execution. If this is something you would use a lot, you can just put the command in a file and use sed -f to run it.

like image 165
MattoxBeckman Avatar answered Sep 20 '22 17:09

MattoxBeckman


If you are okay with Perl you can do:

$ cat FILE1
this is file1

$ cat FILE2
this is file2

$ cat file
foo
INSERT_HERE1
bar
INSERT_HERE2
baz

$ perl -ne 's/^INSERT_HERE(\d+)\s+$/`cat FILE$1`/e;print' file
foo
this is file1
bar
this is file2
baz
$ 
like image 24
codaddict Avatar answered Sep 20 '22 17:09

codaddict