GNU awk
这是使用和的一种方法rev
像这样运行:
awk -f ./script.awk <(echo "hello" | cowsay){,} | rev
内容script.awk
:
FNR==NR {
if (length > max) {
max = length
}
next
}
{
while (length < max) {
$0=$0 OFS
}
}1
或者,这是单线:
awk 'FNR==NR { if (length > max) max = length; next } { while (length < max) $0=$0 OFS }1' <(echo "hello" | cowsay){,} | rev
结果:
_______
> olleh <
-------
^__^ \
_______\)oo( \
\/\) \)__(
| w----||
|| ||
-------------------------------------------------- ------------------------------------------
这是另一种使用方式GNU awk
:
像这样运行:
awk -f ./script.awk <(echo "hello" | cowsay){,}
内容script.awk
:
BEGIN {
FS=""
}
FNR==NR {
if (length > max) {
max = length
}
next
}
{
while (length < max) {
$0=$0 OFS
}
for (i=NF; i>=1; i--) {
printf (i!=1) ? $i : $i ORS
}
}
或者,这是单线:
awk 'BEGIN { FS="" } FNR==NR { if (length > max) max = length; next } { while (length < max) $0=$0 OFS; for (i=NF; i>=1; i--) printf (i!=1) ? $i : $i ORS }' <(echo "hello" | cowsay){,}
结果:
_______
> olleh <
-------
^__^ \
_______\)oo( \
\/\) \)__(
| w----||
|| ||
-------------------------------------------------- ------------------------------------------
解释:
这是第二个答案的解释。我假设有以下基本知识awk
:
FS="" # set the file separator to read only a single character
# at a time.
FNR==NR { ... } # this returns true for only the first file in the argument
# list. Here, if the length of the line is greater than the
# variable 'max', then set 'max' to the length of the line.
# 'next' simply means consume the next line of input
while ... # So when we read the file for the second time, we loop
# through this file, adding OFS (output FS; which is simply
# a single space) to the end of each line until 'max' is
# reached. This pad's the file nicely.
for ... # then loop through the characters on each line in reverse.
# The printf statement is short for ... if the character is
# not at the first one, print it; else, print it and ORS.
# ORS is the output record separator and is a newline.
您可能需要了解的其他一些事项:
{,}
通配符后缀是重复输入文件名两次的简写。不幸的是,它不是标准的 Bourne shell。但是,您可以改为使用:
<(echo "hello" | cowsay) <(echo "hello" | cowsay)
此外,在第一个示例中,{ ... }1
是{ ... print $0 }
HTH。