Bourne Shell Left Right Justify

南楼画角 提交于 2019-11-28 02:06:06

问题


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?


回答1:


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



回答2:


You're not being very clear, but the easiest way is probably to just use printf() (the shell command, not the C function of the same name).




回答3:


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"



回答4:


Pipe it through fmt? Not actually bourne shell specific, but still...




回答5:


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"



回答6:


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";


来源:https://stackoverflow.com/questions/2199843/bourne-shell-left-right-justify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!