I have few lines to be inserted in file_lines_to_insert.
In another file final_file, I have to add lines from above file file_lines_to_insert before a particular pattern.
e.g.
$ cat file_lines_to_insert => contents are
abc
def
lkj
In another file final_file, before a pattern "PIN (new)", I want to insert above file contents.
Pl. tell me how to do it with sed command if possible.
Unfortunately sed's r command only appends. If your pattern doesn't appear on the first line (in which case you can just cat the insert file before the final file):
x=$(sed '/PIN (new)/!d;=;d;q' final-file)
# check if x has value and not 1
# ...
sed "$((x-1))r inser-file" final-file
'/PIN (new)/r file_lines_to_insert' => When this pattern matches lines from file_lines_to_insert in inserted.
'x' => This command helps to switch the content of pattern buffer with hold buffer. So when 1st line is read 'x' puts the 1st line to hold buffer
and pattern buffer takes a new-line char, after this switch what ever there is in pattern buffer is printed, that's why a new line is printed
first in the output.
Now 2nd line is read, 'x' puts 2nd line into hold buffer and line 1 which is already in hold buffer comes to pattern buffer and line 1 now gets printed.
This action repeats for all the remaining lines.