I am trying to do some formatting on output data in a script and not positive how to do Left Right justify as well as width. Can anyone point me in the right direction?
A:
Left align is kind of trivial, to get right align you can use printf
and the envrironment variable $COLUMNS
like that:
printf "%${COLUMNS}s" "your right aligned string here"
gregseth
2010-02-04 13:40:48
+1
A:
you can use printf. examples
$ printf "%15s" "col1"
$ printf "%-15s%-15s" "col1" "col2"
tools like awk also has formatting capabilities
$ echo "col1 col2" | awk '{printf "%15s%15s\n", $1,$2}'
col1 col2
ghostdog74
2010-02-04 13:41:14
A:
You can do it using pure bash:
x="Some test text"
width=" " # 20 blanks
echo "${width:0:${#width}-${#x}}$x"
Output is:
' Some test text' (obviously without the quotes)
So the two things you need to know is ${#var} will get the length of the string in var, and ${var:x:y} extracts a string from x to y positions.
You may need a recent version (tested on GNU bash 3.2.25)
EDIT: Come to think of it, you can do it like this:
echo "${width:${#x}}$x"
jamesj629
2010-02-04 13:59:57
the title is bourne.
ghostdog74
2010-02-04 14:02:48
Is Bourne not bash? As in Bourne Again SHell?
jamesj629
2010-02-05 13:55:59
A:
Here is a Perl script that does full justification and hyphenation.
Here is a diff to add a left margin feature to that script:
--- paradj.pl 2003-11-17 09:45:21.000000000 -0600
+++ paradj.pl.NEW 2010-02-04 09:14:09.000000000 -0600
@@ -9,16 +9,18 @@
use TeX::Hyphen;
my ($width, $hyphenate, $left, $centered, $right, $both);
-my ($indent, $newline);
+my ($indent, $margin, $newline);
GetOptions("width=i" => \$width, "help" => \$hyphenate,
"left" => \$left, "centered" => \$centered,
"right" => \$right, "both" => \$both,
+ "margin:i" => \$margin,
"indent:i" => \$indent, "newline" => \$newline);
my $hyp = new TeX::Hyphen;
syntax() if (!$width);
$indent = 0 if (!$indent);
+$margin = 0 if (!$margin);
local $/ = "";
@@ -147,6 +149,7 @@
}
}
+ print " " x $margin;
print "$lineout\n";
}
}
@@ -185,6 +188,9 @@
print "initial\n";
print " indention (defaults ";
print "to 0)\n";
+ print "--margin=n (or -m=n or -m n) Add a left margin of n ";
+ print "spaces\n";
+ print " (defaults to 0)\n";
print "--newline (or -n) Output an empty line \n";
print " between ";
print "paragraphs\n";
Dennis Williamson
2010-02-04 14:51:23