1

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

2 Answers 2

6

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
6
  • Its not working , it completely removed the other characters and fill the line with zeroes only
    – Mirage
    Feb 6, 2013 at 8:02
  • it works fine for me, added the output above..
    – Guru
    Feb 6, 2013 at 8:04
  • I get this as ouput 00000000000000000000 FDSFD 000000000000HGHGF HHGDF 0000000000000000000 GFDGFDGFDGDFGDGD
    – Mirage
    Feb 6, 2013 at 8:12
  • 1
    @user1544681: I'm guessing you need to convert your file to have unix line endings.
    – Thor
    Feb 6, 2013 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
    – Mirage
    Feb 6, 2013 at 8:44
4

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .