If you want answers using tools that are CSV-aware to account for CSV files containing fields with embedded |
characters and newlines, then here's how you do it with mlr
(Miller):
mlr --csv --fs '|' -N filter -S '${4} =~ "^5"' file
This makes mlr
read the original data as a header-less CSV file using |
as the field separator (this is what --csv --fs '|' -N
does). It applies a filter expression that extracts the records for which the expression is true. While doing so, it avoids inferring data types and treats the data as strings (-S
, because regular expressions are generally only applicable to strings).
The expression matches the regular expression ^5
to the fourth field of the record.
Extracted records are reproduced as CSV with the same field separator as the input.
You can do the same sort of thing with the tools from the csvkit package, but since there's no way to tell csvgrep
to use a custom field separator for the output, you will have to reformat the result with csvformat
if you want to retain your |
separators:
csvgrep -d '|' -H -c 4 -r '^5' file | csvformat -K 1 -D '|'
The -K 1
options to csvformat
skips the anonymous header line produced by csvgrep
.