Skip to content
Advertisement

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

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

Advertisement

Answer

You need spaces around the =~ operator. Compare:

[[ foo=~bar ]]
[[ foo =~ bar ]]

This is because the first expression essentially evaluates as “Is this string empty?”

Also, the OP code uses small tilde rather than tilde.

Even so, you can easily get rid of the inner loop. Just replace the whole while read -r line2 bit with cat -- "$second_filename".

Your last echo $line is only correct if the file does not end in a newline character (standard with *nix tools). Instead, you should use while read -r line || [[ $line ~= '' ]]. This works with or without newline at the end.

Also, Use More Quotes™.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement