Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a task which requires some awk scripting:

Lets say I have a file:


How could I make it look like this using awk?


In other words, I want to expand first field along the column.

share|improve this question
Regarding pros and cons of setting awk variables as command paramaters vs. as command ooptions, see: Are there 2 ways to set awk vars via command line?. The -v(option) syntax was introduced to deal with potential pitfalls of the paramater method shown in the two (current) answers. – Peter.O Jan 17 '13 at 6:52

One way:

$ awk -F, '!$1{$1=p;}$1{p=$1;}1' OFS=, file

$1{p=$1;} When $1 has a value, store it in a variable p

!$1 Mean $1 is empty. When $1 is empty, set $1 with p which contains the last $1 value.

1 to print every line.

share|improve this answer
It is just what I was searching for. Thanks very much! – user30422 Jan 17 '13 at 5:25
!$1 does not only mean $1 is empty. You should change it to $1 == "" or otherwise, you may have issues if the first field may be for instance 0 – Stéphane Chazelas Jan 18 '13 at 16:00
@user30422 If this answer solved your problem, please remember to mark it as accepted and/or upvote it instead of posting a thank you comment. That is the way thanks are expressed on SE sites. – terdon Feb 11 '13 at 18:15

another solution:

awk -F, '{$1=$1?P=$1:P;print}' OFS=,

sets P to $1 if $1 not empty. sets $1 to previous P otherwise

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.