Monday, October 24, 2022

[SOLVED] Replace pattern with consecutive strings from list

Issue

I would like to find specific string in one file and then replace it with consecutive strings from another file. The order of replacement should be maintained.

The first file looks like this:

>A1
NNNNNNNNNN
NNNNNNNNNN
>B2
ACGTNNNNNN
NNNGTGTNNN
NNNNNNNNNN
>B3
GGGGGGGGGG
NNNTTTTTTT
NNNNCTGNNN

And the file with strings looks like this:

Name1
Name1
Name2
Name2
Name3
Name4

So finally I would like to find lines containing '>' and replace '>' with '>string' from second file to get this output:

>Name1 A1
NNNNNNNNNN
NNNNNNNNNN
>Name1 B2
ACGTNNNNNN
NNNGTGTNNN
NNNNNNNNNN
>Name2 B3
GGGGGGGGGG
NNNTTTTTTT
NNNNCTGNNN

Solution

If you have GNU sed:

sed '/^>/R file_with_strings' first_file | sed '/^>/{N;s/>\(.*\)\n\(.*\)/>\2 \1/;}'


Answered By - M. Nejat Aydin
Answer Checked By - Willingham (WPSolving Volunteer)