Alexander Mills
Alexander Mills

Reputation: 100010

Replace string in one file with contents of another file

I am looking for a BASH program that I can run to replace a matching string in file2 with all of the contents from file1.

So file2 looks like this:

define([
 'require'
  ****
 ],
 function(require){
 });

file1 looks like:

, 'app/js/controllers/x'
, 'app/js/controllers/y'
, 'app/js/controllers/z'

is there a simple BASH script I can use to copy the 3 lines from file1 and replace the **** string with the file1 contents and then write the result to file3.js?

Upvotes: 2

Views: 7356

Answers (3)

blashser
blashser

Reputation: 1031

There is a simple sed command:

sed -i '/\*\*\*\*/ { r file1\nd }' file2

You are telling sed two things:

  • Find string **** , read the file1 and append it.

  • Delete string ****.

You need the curly braces to concatenate the orders.

Append the content of a file when sed match your string/regex:

sed '/yourString/r fileToAppend' inputFile.

Delete a string:

sed '/yourStringToDelete/d' inputFile

Upvotes: 2

John1024
John1024

Reputation: 113834

Using sed

$ sed $'/[*][*][*][*]/{r file1\nd}' file2
define([
 'require'
, 'app/js/controllers/x'
, 'app/js/controllers/y'
, 'app/js/controllers/z'
 ],
 function(require){
 });

This looks for the line containing ****. When found, it reads file and then deletes the line containing ****.

Using awk:

$ awk 'FNR==NR{s=s"\n"$0;next;} /[*][*][*][*]/{$0=substr(s,2);} 1' file1 file2
define([
 'require'
, 'app/js/controllers/x'
, 'app/js/controllers/y'
, 'app/js/controllers/z'
 ],
 function(require){
 });

The first file is read into variable s. When we see **** in the second file, we replace it with s from the first file.

Upvotes: 6

Victory
Victory

Reputation: 5890

You can read in the file line by line, and if you find the 4 stars in a row, instead of just printing the line, cat out file1. I use tee to print to newfile.txt and the terminal.

#!/bin/bash

FILE1="file1.txt"
FILE2="file2.txt"

# read line by line
while IFS=''  read -r line || [[ -n "$line" ]]; do
   # if we don't find 4 * in a row just print the line
   if [ $line != *"****"* ]; then 
        echo "$line"
   else
        cat $FILE1 # we found 4 stars, print the data from FILE1
   fi

done < "$FILE2" | tee newfile.txt                           

Upvotes: 1

Related Questions