Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Inserting one file's content into another file after the pattern

Tags:

linux

bash

shell

sh

I'm trying to write a bash script, which will do the following:

  1. reads the content from the first file (as a first argument)
  2. reads the content from the second file (as a second argument)
  3. finds the line in the second file with the given pattern (as a third argument)
  4. inserts text from the first file to the second file after the line of the pattern.
  5. prints final file on the screen.

For example:

first_file.txt:

111111
1111
11
1

second_file.txt:

122221
2222
22
2

pattern:

2222

output:

122221
111111
1111
11
1
2222
111111
1111
11
1
22
2

What should I use to realize this functionality on BASH?

I wrote the code, but it doesn't work properly (why?):

    #!/bin/bash

    first_filename="$1"
    second_filename="$2"
    pattern="$3"

    while read -r line
    do
    if [[ $line=˜$pattern ]]; then
            while read -r line2
            do
                    echo $line2
            done < $second_filename
    fi
    echo $line
    done < $first_filename
like image 521
user2431907 Avatar asked May 29 '13 10:05

user2431907


People also ask

How do I append the contents of one file to another?

You can use cat with redirection to append a file to another file. You do this by using the append redirection symbol, ``>>''. To append one file to the end of another, type cat, the file you want to append, then >>, then the file you want to append to, and press <Enter>.

How do I add content to a file in bash?

To make a new file in Bash, you normally use > for redirection, but to append to an existing file, you would use >> . Take a look at the examples below to see how it works. To append some text to the end of a file, you can use echo and redirect the output to be appended to a file.


1 Answers

sed can do that without loops. Use its r command:

sed -e '/pattern/rFILE1' FILE2

Test session:

$ cd -- "$(mktemp -d)" 
$ printf '%s\n' 'nuts' 'bolts' > first_file.txt
$ printf '%s\n' 'foo' 'bar' 'baz' > second_file.txt
$ sed -e '/bar/r./first_file.txt' second_file.txt
foo
bar
nuts
bolts
baz
like image 173
choroba Avatar answered Sep 17 '22 07:09

choroba