Replace blank value with previous first column value using awk and sed

awksedtext processing

john    math
        science
paul    math
        science
rosy    math
jill    science
rob     math
        science
hary    math

Desired output:

john    math
john    science
paul    math
paul    science
rosy    math
jill    science
rob     math
rob     science
hary    math

Best Answer

Using awk, by acting upon number of fields

$ awk 'NF==1{print p "\t" $1; next} {p=$1} 1' ip.txt
john    math
john    science
paul    math
paul    science
rosy    math
jill    science
rob     math
rob     science
hary    math
  • {p=$1} 1 for lines other than single field, save first column and print the line
  • NF==1{print p "\t" $1; next} if only one field is present, print previous field, tab and the field from input line. next will skip rest of statements and process next line


if tab separation doesn't work out, use column

$ awk 'NF==1{print p,$1; next} {p=$1} 1' ip.txt | column -t
john  math
john  science
paul  math
paul  science
rosy  math
jill  science
rob   math
rob   science
hary  math
Related Question