Skip to content

Commit 37e6163

Browse files
authored
Using awk to add a prefix
1 parent c773c5a commit 37e6163

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

bash/use-awk-to-add-a-prefix.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Using awk to add a prefix
2+
3+
I wanted to dynamically run the following command against all files in a directory:
4+
5+
```bash
6+
pypi-to-sqlite content.db -f /tmp/pypi-datasette-packages/packages/airtable-export.json \
7+
-f /tmp/pypi-datasette-packages/packages/csv-diff.json \
8+
--prefix pypi_
9+
```
10+
11+
I can't use `/tmp/pypi-datasette-packages/packages/*.json` here because I need each file to be processed using the `-f` option.
12+
13+
I found a solution using `awk`. The `awk` program `'{print "-f "$0}'` adds a prefix to the input, for example:
14+
```
15+
% echo "blah" | awk '{print "-f "$0}'
16+
-f blah
17+
```
18+
I wanted that trailing backslash too, so I used this:
19+
20+
```awk
21+
{print "-f "$0 " \\"}
22+
```
23+
Piping to `awk` works, so I combined that with `ls ../*.json` like so:
24+
25+
```
26+
% ls /tmp/pypi-datasette-packages/packages/*.json | awk '{print "-f "$0 " \\"}'
27+
-f /tmp/pypi-datasette-packages/packages/airtable-export.json \
28+
-f /tmp/pypi-datasette-packages/packages/csv-diff.json \
29+
-f /tmp/pypi-datasette-packages/packages/csvs-to-sqlite.json \
30+
```
31+
Then I used `eval` to execute the command. The full recipe looks like this:
32+
```bash
33+
args=$(ls /tmp/pypi-datasette-packages/packages/*.json | awk '{print "-f "$0 " \\"}')
34+
eval "pypi-to-sqlite content.db $args
35+
--prefix pypi_"
36+
```
37+
Full details in [datasette.io issue 98](https://github.com/simonw/datasette.io/issues/98).

0 commit comments

Comments
 (0)