Pass Parameters to awk command

I need to pass values at runtime for the below awk command where

l is the length and partial.txt is the file name.

 
awk -v l=285 '{s="%-"l"s\n";printf(s,$0);}' partial.txt > temp1.txt;
FILE="partial.txt"
LEN=285

echo | awk -v l="$LEN" -v file="$FILE" '{s="%-"l"s\n"; while(( getline line < file  ) > 0 ) { print s,line; } } '
1 Like

The parameters i need to pass are

FILE = <filepath>/partial.txt

When i replace the filepath it gives error as "cannot open the file for reading"

It should work! Make sure you do not have any blank space between assignment operator = and wrap the string variable value in double quotes " to avoid any unexpected behavior.

 
#!/bin/ksh
FILE=$1
LEN=$2
echo | awk -v l="$LEN" -v file="$FILE" '{s="%-"l"s\n";printf(s,$0);}' file > temp1.txt;

I execte the script using the below command

 
sh -x Script.sh /home/dhandal/partial.txt 285

Let me know whether i am executing right.

Rather try

awk -v l="$LEN"  '{s="%-"l"s\n";printf(s,$0);}' $FILE > temp1.txt;

or

awk -v l="$2"  '{s="%-"l"s\n";printf(s,$0);}' $1 > temp1.txt;
1 Like