Left padding in Unix


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Left padding in Unix
# 1  
Old 12-13-2011
Left padding in Unix

I am passing input string,length, and the pad character.

Code:
input string=123
Pad char=#
Length=6

then the output should be:

Code:
###123

How we can do this?

Thanks
# 2  
Old 12-13-2011
awk, perl, c, or shell (if shell, which shell?) ?
# 3  
Old 12-13-2011
AWK or KSH.
# 4  
Old 12-13-2011
Code:
#!/bin/ksh
lpad()
{
   if [ $# -eq 3 ] ; then
     echo "$1" | awk -v pad="$2" -v len=$3 '{
        if(length($0) >= len) {print $0; exit}
        for(i=0;i<len - length($0);i++) { tmp=tmp pad }
        print tmp $0 }'
   else
     echo "Invalid parms for lpad" > 2   
   fi
}

# usage / test
val=$(lpad "test string" "0" 14); echo "$val"
val=$(lpad 1234 "#"  4);  echo "$val"
val=$(lpad 1234 "#"  8);  echo "$val"

# 5  
Old 12-14-2011
Here is a solution using pure ksh - it's much bigger that the version that spawns awk but you do get substr() and fill() functions at no extra cost:

Code:
substr() {
  # string start [length]
  str="$1"
  start=$(( $2 ))
  let end=${#str}-$start-$(( ${3:-9999} ))+1
  [ $start -gt ${#str} ] && return
  for chop in "??????????" "????" "?"
  do
    while [ $start -gt ${#chop} ]
    do
      str="${str#$chop}"
      let start=start-${#chop}
    done
    while [ $end -ge ${#chop} ]
    do
        str="${str%$chop}"
        let end=end-${#chop}
    done
  done
  printf "$str"
}
fill() {
    # fill count [chars]
    FILL="${2:- }"
    chars=$(( $1 ))
    c=0
    while [ $c -le $chars ]
    do
        printf "%s" "$(substr "$FILL" 1 ${chars}-$c )"
        let c=c+${#FILL}
    done
}
lpad() {
  # lpad width string [chars]
  let PAD=$1-${#2}
  if [ $PAD -lt 1 ]
  then
    substr "$2" 1 $1-1
  else
    fill $PAD "$3"
    printf %s "$2"
  fi
}
 
#and now some tests
echo $(lpad 14 "test string" ".-")
echo $(lpad 4 1234 "#")
echo $(lpad 8 1234 "#")


output:
Code:
.-.test string
123
####1234

This User Gave Thanks to Chubler_XL For This Post:
# 6  
Old 12-14-2011
@pandeesh: Try Perl.
Code:
perl -e '$str="123";$pad="#";$len=3;print (($pad x $len) . $str)'

Just a funny note. No offense intended Smilie
Master Foo and the Ten Thousand Lines
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Padding a csv value with 0's

I have this csv file that I would like to sort on the 20th and 21st field. They are high lighted below. My challenge is that when I sort on those fields they are not in order as I would have liked. It seems like I have to pad those fields to the longest value in that fields data. ... (6 Replies)
Discussion started by: GroveTuckey
6 Replies

2. Shell Programming and Scripting

awk to substitute ip without zero left padding

Hello All, I have this script to awk IP to new file. #awk '/myip|yourip/ {sub(/...\....\....\..../, newip)}1' newip=$IP existing.txt > new.txt When existing.txt has myip=192.168.123.123 and $IP has 192.168.12.12, the awk script is not working. But while I add zero left padding to $IP i.e,... (3 Replies)
Discussion started by: Shaan_Shaan
3 Replies

3. Shell Programming and Scripting

Left Join in Unix based on Key?

So I have 2 files: File 1: 111,Mike,Stipe 222,Peter,Buck 333,Mike,Mills File 2: 222,Mr,Bono 444,Mr,Edge I want output to be below, where 222 records joined and all none joined records still in output 111,Mike,Stipe 222,Peter,Buck,Mr,Bono 333,Mike,Mills 444,Mr,Edge (4 Replies)
Discussion started by: stack
4 Replies

4. Shell Programming and Scripting

Unix Cut or Awk from 'Right TO Left'

Hello, I want to get the User Name details of a user from a file list. This list can be in the format: FirstName_MiddleName1_LastName_ID FirstName_LastName_ID FirstName_MiddleName1_MiddleName2_LastName_ID What i want it to return is FirstName_MiddleName1_LastName of a user. I... (6 Replies)
Discussion started by: limamichelle
6 Replies

5. Shell Programming and Scripting

Padding with zeros.

Hi Friends, I would like to left pad with "0's" on first column say (width six) I have a large file with the format: FILE: 1: ALFRED 84378 NY 8385: JAMES 88385 FL 323: SMITH 00850 TX My output needs to be like: 000001: ALFRED 84378 NY 008385: JAMES 88385 FL 000323: SMITH... (10 Replies)
Discussion started by: sbasetty
10 Replies

6. UNIX for Dummies Questions & Answers

Zero padding dates

I have a file with records containing dates like: SMPBR|DUP-DO NOT USE|NEW YORK||16105|BA5270715|2007-6-6|MWERNER|109||||JOHN||SMITH|MD|72211118||||||74559|21 WILMINGTON RD||D|2003-11-6|SL# MD CONTACT-LIZ RICHARDS|||0|Y|N||1411458| How can I get the date fields in each of my records to be... (1 Reply)
Discussion started by: ChicagoBlues
1 Replies

7. Shell Programming and Scripting

Padding in Unix

I have a file with different character counts on each line how do i make it with unique character counts. example: 1st line : ABCD 011 XYZ 0000 YYYY BBB TEADINGDA 2nd line: ABCD 011 xys 0010 YYYY BBB TEAD 3rd line : ABCD 022 YXU 000 UUU BBB TE 1st line is 43... (3 Replies)
Discussion started by: rudoraj
3 Replies

8. Programming

Padding variables

Is there a function in c that will allow me to pad variables? I have an int that can't be longer than 10. I need to pad a numeric value with leading zeros 314 0000000314 (1 Reply)
Discussion started by: flounder
1 Replies

9. UNIX for Dummies Questions & Answers

left padding numbers

Hi, can someone please tell me how to left-pad numbers using unix. e.g. 1234 -> 00001234 Thanks in advance for your help. (1 Reply)
Discussion started by: colquhoi
1 Replies

10. UNIX for Dummies Questions & Answers

Padding

Hi Can anyone tell me how to pad zeroes on the left side to a numeric string in unix shell scripting Your answer is very much appreciated Thanks Vijay (2 Replies)
Discussion started by: vijaygopalsk
2 Replies
Login or Register to Ask a Question