我试图将Bash数组拆分为多列,以便在Markdown文件中显示为表格。
我已经搜索了一种快速的单行代码,以使用Bash,AWK和其他语言来执行此操作。我知道column
命令,但是无法将输出保存到变量或文件(stdout
)中。我知道您可以循环数组,将值提取到单独的块中,但是必须有一种更快,更有效的方法。
awk
accessibility
bash
behat
c++
cache
d3.js
dates
engineering
elasticsearch
...
local data="$(sort "keywords.md")" # read contents of file
local data=($data) # split contents into an array
local table="||||||\n" # create markdown table header
table="${table}|---|---|---|---|---|"
local numColumns=5
# split data into five columns and append to $table variable
我正试图得到这个结果。
||||||
|---|---|---|---|---|
|awk|bash|c++|d3.js|engineering
|accessibility|behat|cache|dates|elasticsearch
答案 0 :(得分:0)
这是一般方法:
$ cat tst.awk
BEGIN {
numCols = (numCols ? numCols : 5)
OFS = "|"
}
{
colNr = (NR - 1) % numCols + 1
if ( colNr == 1 ) {
numRows++
}
vals[numRows,colNr] = $0
}
END {
hdr2 = OFS
for (colNr=1; colNr<=numCols; colNr++) {
hdr2 = hdr2 "---" OFS
}
hdr1 = hdr2
gsub(/-/,"",hdr1)
print hdr1 ORS hdr2
for (rowNr=1; rowNr<=numRows; rowNr++) {
printf "|"
for (colNr=1; colNr<=numCols; colNr++) {
val = vals[rowNr,colNr]
printf "%s%s", val, (colNr<numCols ? OFS : ORS)
}
}
}
。
$ awk -f tst.awk file
||||||
|---|---|---|---|---|
|awk|accessibility|bash|behat|c++
|cache|d3.js|dates|engineering|elasticsearch
但是它显然不会按照您在问题中要求的顺序输出列,因为我不知道您是如何得出该顺序的。
答案 1 :(得分:0)
这是一个perl版本,可以打印出按列减少的值,如您的示例所需输出中一样:
import React, { Fragment, useState } from "react";
import { connect } from "react-redux";
import { addBid } from "../../actions/listing";
import PropTypes from "prop-types";
const BidForm = ({ test, listingId, addBid }) => {
const [price, setBid] = useState("");
return (
<Fragment>
<h1 className="large text-primary">Bid</h1>
<form
className="form-1"
onSubmit={e => {
addBid(listingId, { price });
}}
>
<div className="form-group pb">
<input
type="text"
placeholder="Price"
name="price"
value={price}
onChange={e =>
setBid(e.target.value) & (parseFloat(price) > parseFloat(test))
? console.log("greater")
: console.log("less than")
}
/>
</div>
<input type="submit" className="btn btn-primary my-1" />
</form>
</Fragment>
);
};
BidForm.propTypes = {
addBid: PropTypes.func.isRequired
};
export default connect(
null,
{ addBid }
)(BidForm);
用法:
#!/usr/bin/perl
use warnings;
use strict;
use feature qw/say/;
my $ncolumns = 5;
# Read the list of values.
my @data;
while (<>) {
chomp;
push @data, $_;
}
# Partition the data up into rows, added down by column
my @columns;
my $nrows = @data / $ncolumns;
#@data = sort { $a cmp $b } @data;
while (@data) {
my @c = splice @data, 0, $nrows;
for my $n (0 .. $#c) {
push @{$columns[$n]}, $c[$n];
}
}
# And print them out
say '|' x $ncolumns;
say '|', join('|', ('---') x $ncolumns), '|';
for my $r (0 .. $nrows - 1) {
my @row;
for my $c (0 .. $ncolumns - 1) {
my $item = $columns[$r]->[$c];
push @row, $item if defined $item;
}
push @row, ('')x$ncolumns;
say '|', join('|', @row[0 .. $ncolumns - 1]);
}