看起来并不那么简单。至少对于我来说。
我需要在printf文本中有一个变量。 它类似于:
FOO="User data"
+++++++++++++++++++ $FOO +++++++++++++++++++++
输出
+++++++++++++++++++ User Data +++++++++++++++++++++
但是
FOO="Fooooooo barrrr"
+++++++++++++++++++ $FOO +++++++++++++++++++++
应输出
++++++++++++++++ Fooooooo barrrr ++++++++++++++++++
和
FOO="Foooooooooooooooooooo barrrrr"
+++++++++++++++++++ $FOO +++++++++++++++++++++
应该是
+++++++++ Foooooooooooooooooooo barrrrr +++++++++++
正如您所看到的,我需要一个变量位于n长度线的中间,由+
标记包围。如何使用printf和其他默认可用命令实现?
(Debian 8)
答案 0 :(得分:6)
foo="stackoverflow.com"
输出:
+++++++++++++++++++ User data ++++++++++++++++++++
使用System.register("foo", [], function(exports_1) {
"use strict";
var App;
return {
setters:[],
execute: function() {
App = (function () {
function App() {
this.bar = 'Hello world.';
console.log(this.bar);
}
return App;
})();
exports_1("App", App);
;
}
}
});
System.register("bar", ["foo"], function(exports_1) {
"use strict";
var App;
return {
setters:[],
execute: function() {
App = (function () {
function App() {
this.bar = 'Mony a mickle maks a muckle.';
console.log(this.bar);
}
return App;
})();
exports_1("App", App);
;
}
}
});
:
+++++++++++++++ stackoverflow.com ++++++++++++++++
答案 1 :(得分:2)
#!/usr/bin/env bash
linelen=100
char="+"
text=$1
len=$(echo -n $text | wc -m)
fillerlen=$((($linelen - $len - 2) / 2))
filler=$(printf "$char%.0s" $(seq 1 $fillerlen))
echo $filler $text $filler
答案 2 :(得分:2)
在printf
的格式字符串中,您可以使用%${p}s
指定字符串的“精度”,其中$p
是精度。您可以通过打印所需的次数(扩展到空格)然后将空格转换为“+”来利用它:
$ p=10
$ printf "%${p}s\n" | tr ' ' +
++++++++++
这个函数取你的线的长度和你想放在它中心的字符串,然后用加号打印它:
pad () {
len=$1
string=$2
# ${#string} expands to the length of $string
n_pad=$(( (len - ${#string} - 2) / 2 ))
printf "%${n_pad}s" | tr ' ' +
printf ' %s ' "$string"
printf "%${n_pad}s\n" | tr ' ' +
}
像这样工作:
$ pad 50 Test
++++++++++++++++++++++ Test ++++++++++++++++++++++
$ pad 50 "A longer string to be padded"
++++++++++ A longer string to be padded ++++++++++
注意你必须引用由多个单词组成的字符串,或者只使用第一个单词。
如果您的线的长度不能被2整除,则填充将向下舍入,但始终是对称的。
答案 3 :(得分:1)
试试这个:
#!/bin/bash
n=50; # You can change the value of n as you please.
var="fooo baar";
size=${#var}
n=$(( n - size ))
n=$(( n / 2 ))
s=$(printf "%-${n}s" "*")
echo "${s// /*} "$var" ${s// /*}" #white-spaces included here.