Search code examples
shellawkgreplinesprefix

Add prefix to a line from the line before it in shell


I am executing following command to get the lines that have to be added prefix to from the line above it as follows:

 grep -B1 "^E[0-9]"

and I am getting something as follows:

ENSG00000165661:E5.1
E6.1
--
ENSG00000174776:E7.1
E8.1
--
ENSG00000122482:E7.2
E8.1

How do I add prefix to the lines that start with E[alphanumeric] such that the file becomes

 ENSG00000165661:E5.1
 ENSG00000165661:E6.1
 ENSG00000174776:E7.1
 ENSG00000174776:E8.1
 ENSG00000122482:E7.2
 ENSG00000122482:E8.1

Solution

  • awk to the rescue!

     awk -F: '/^E[0-9]/{print p0; print p1 FS $0} {p1=$1; p0=$0}' file
    

    untested since no testable data

    Explanation

    when pattern match print the previous line stored in variable p0; then print the first field (p1) of the previous line, field separator (FS) and the current line ($0). The next statement will set the p0 and p1 variables for each line whether it will be used or not since there is no look ahead.