Using Raku (formerly known as Perl_6)
~$ raku -ne '.put unless grep {.chars == 0}, .split(",")[0..*-2]' file
OR:
~$ raku -ne 'given .split(",", :skip-empty) {.join(",").put if .elems > 3}' file
The first answer above is very similar to the Perl answer given by @StéphaneChazelas (Thank you, Stéphane!). Since the lines end with a comma (which can be interpreted as a trailing blank column), the index [0..*-2]
is used which drops this last (empty) element. This code retains rows with all filled columns (excepting the final empty column) and will drop lines if blank columns are found even after the first 4 fields. Use .split(",")[0..3]
if you want to restrict the requirement to the first four fields (elements).
Note, *-1
is the last element of an array-like structure in Raku, while something like [0..*]
also works (means 'give me everything'). Raku has "Zen slices" as well, so .split(",")[]
is valid syntax.
The second answer uses the fact that Raku's split
routine has a :skip-empty
parameter (i.e. "adverb") which can take the place of grep
ping for .chars == 0
. So you are left with deciding how many columns are required in the output. Here .elems > 3
asks for a minimum of 4 columns.
Technically, the second answer is the correct answer, because the first answer leaves the trailing comma in place, while the second answer removes it.
Sample Input:
aaaa,bbbb,cccc,dddd,
,bbbb,cccc,dddd,
aaaa,,cccc,dddd,
aaaa,,,dddd,
,,,dddd,
Sample Output (first answer):
aaaa,bbbb,cccc,dddd,
Sample Output (second answer):
aaaa,bbbb,cccc,dddd
https://docs.raku.org
https://raku.org