Database Reference
In-Depth Information
And last but not least, we can apply a command to just the header, similar to what the
body
command-line tool does to the body:
$
seq 5 | header -a line | header -e
"tr '[a-z]' '[A-Z]'"
LINE
1
2
3
4
5
The third command-line tool is called
cols
, which is similar to
header
and
body
in
that it allows you to apply a certain command to only a subset of the columns. The
code is as follows:
#!/usr/bin/env bash
ARG
=
"$1"
shift
COLUMNS
=
"$1"
shift
EXPR
=
"$@"
DIRTMP
=
$(
mktemp -d
)
mkfifo
$DIRTMP
/other_columns
tee
$DIRTMP
/other_columns | csvcut
$ARG
$COLUMNS
|
${
EXPR
}
|
paste -d, - <
(
csvcut
${
ARG
~~
}
$COLUMNS
$DIRTMP
/other_columns
)
rm -rf
$DIRTMP
For example, if we wanted to uppercase the values in the
day
column in the
tips.csv
data set (without affecting the other columns and the header), we would use
cols
in
combination with
body
, as follows:
$
< tips.csv cols -c day body
"tr '[a-z]' '[A-Z]'"
| head -n 5 | csvlook
|------+-------+------+--------+--------+--------+-------|
| day | bill | tip | sex | smoker | time | size |
|------+-------+------+--------+--------+--------+-------|
| SUN | 16.99 | 1.01 | Female | No | Dinner | 2 |
| SUN | 10.34 | 1.66 | Male | No | Dinner | 3 |
| SUN | 21.01 | 3.5 | Male | No | Dinner | 3 |
| SUN | 23.68 | 3.31 | Male | No | Dinner | 2 |
|------+-------+------+--------+--------+--------+-------|
Note that passing multiple command-line tools and arguments as commands to
header -e
,
body
, and
cols
can lead to tricky quoting situations. If you ever run into
such problems, it is best to create a separate command-line tool for this and pass that
as the command.
In conclusion, while it is generally preferable to use command-line tools that are
specifically made for CSV data,
body
,
header
, and
cols
also allow you to apply the
classic command-line tools to CSV files if needed.