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:

JavaScript

second_file.txt:

JavaScript

pattern:

JavaScript

output:

JavaScript

What should I use to realize this functionality on BASH?

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

JavaScript

Advertisement

Answer

You need spaces around the =~ operator. Compare:

JavaScript

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