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 this file. I want to use only sed, no awk

FSDFDSFSD
FDSFD
FHGDHFDHGHFGHGHGF
HHGDF
GFDGDFGFDG
GFDGFDGFDGDFGDGD

I want to fill every odd line appended with 000 so that total characters are 30 in each line

I want output like

FSDFDSFSD0000000000
FDSFD
FHGDHFDHGHFGHGHGF00
HHGDF
GFDGDFGFDG000000000
GFDGFDGFDGDFGDGD
share|improve this question
add comment

2 Answers

One way:

sed -e :a -e 's/^.\{1,29\}$/&0/;ta' -e n file

Match any character(.), and match 1 to 29 characters of the same type(1,29). If match successful, put a '0' behind the pattern matched(&). When the match fails which means when the count of characters excluding the first character exceeds 29, stop it and hence we get the string zero padded by 30.

n at the end simply reads the next line and prints it. This way the even numbered lines get printed untouched.

Executing the above script:

$ sed -e :a -e 's/^.\{1,29\}$/&0/;ta' -e n file
FSDFDSFSD000000000000000000000
FDSFD
FHGDHFDHGHFGHGHGF0000000000000
HHGDF
GFDGDFGFDG00000000000000000000
GFDGFDGFDGDFGDGD
share|improve this answer
    
Its not working , it completely removed the other characters and fill the line with zeroes only –  user1544681 Feb 6 '13 at 8:02
    
it works fine for me, added the output above.. –  Guru Feb 6 '13 at 8:04
    
I get this as ouput 00000000000000000000 FDSFD 000000000000HGHGF HHGDF 0000000000000000000 GFDGFDGFDGDFGDGD –  user1544681 Feb 6 '13 at 8:12
1  
@user1544681: I'm guessing you need to convert your file to have unix line endings. –  Thor Feb 6 '13 at 8:31
    
i tried everything but same. can you give me some sample file where it works , so that i can copy paste that in vm –  user1544681 Feb 6 '13 at 8:44
show 1 more comment

Another approach:

sed 's/$/000000000000000000000000000000/;s/\(.\{30\}\).*/\1/;n'

That would be faster than the iterative approach at appending one character at a time, but note that it would truncate lines that were longer than 30 characters in the first place.

share|improve this answer
add comment

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.