Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a task which requires some awk scripting:

Lets say I have a file:

A,under1
,under2
,under3
,under4
,under5
B,new1
,new2
,new3
C,sm1
,sm2

How could I make it look like this using awk?

A,under1
A,under2
A,under3
A,under4
A,under5
B,new1
B,new2
B,new3
C,sm1
C,sm2

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

2 Answers 2

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

 
discard

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.