I have this input and I would like to learn how to save string after = to variable and use it for output filename and in the first line of output that will start with \"#\"
Could you please try following. On the very first line this will add values of column2
line, RedNumDa
line with hash and then with a new line it will print actual line.
awk '
/ROIysiz/{
second_out=$NF
}
/RedNumDa/{
first_line_value=$NF
}
/c column3/{
third_part=$NF
}
/column2/{
close(out_file)
found=count=""
first_part=$NF
out_file=first_part second_out third_part
next
}
/end header/{
found=1
next
}
found && out_file{
if(++count==1){
print "#" first_part OFS first_line_value ORS $0 > (out_file)
}
else{
print > (out_file)
}
}
' Input_file
Explanation: Adding detailed explanation for above code.
awk ' ##Starting awk program from here.
/ROIysiz/{ ##Checking condition if a line contains string ROIysiz then do following.
second_out=$NF ##Creating variable second_out for output file 2nd part.
}
/RedNumDa/{ ##Checking condition if line contains RedNumDa string in it.
first_line_value=$NF ##Creating variable first_line_value for output file 1st part.
}
/c column3/{ ##Checking condition if line contains column 3 string in it.
third_part=$NF ##Creating variable third_part and setting its value to last field of current line.
}
/column2/{ ##Checking condition if line contains column2 string in it.
close(out_file) ##Closing out_file to avoid "too many files opened" error.
found=count="" ##Nullifying variable found here.
first_part=$NF ##Creating variable first_part which has last part of current line as value.
out_file=first_part second_out third_part ##Creating variable out_file which is having last field of current line and second_out variable value.
next ##next will skip all further statements from here.
}
/end header/{ ##Checking condition if string end header is found then do following.
found=1 ##Setting variable found to 1 here.
next ##next will skip all further statements from here.
}
found && out_file{ ##Checking condition if found AND out_file is SET then do following.
if(++count==1){ ##If count==1 then do following, to add # in starting of first line.
print "#" first_part OFS first_line_value ORS $0 > (out_file) ##Printing # and first_part OFS first_line_value ORS $0.
}
else{ ##Else if count is greater than 1 then do following.
print > (out_file) ##Printing current line to out_file here.
}
}
' Input_file ##Mentioning Input_file name here.