1

I'm looking to delete blank lines in a CSV file, using Perl.

I'm not too sure how to do this, as these lines aren't exactly "blank" (they're just a bunch of commas).

I'd also like to save the output as a file of the same name, overwriting the original.

How could I go about doing this?

edit: I can't use modules or any source code due to network restrictions...

3
  • 1
    Please note that if you can see a module on the web, then you can copy & paste that module into your code. Modules don't have to be installed in order to be useful. Commented Jun 6, 2014 at 13:58
  • 2
    This crossed my mind the other day but for some reason I never actually looked into it whether it was possible... Thanks! Commented Jun 6, 2014 at 14:01
  • I suggest you'll find it hard to do without any source code :-) Commented Jun 9, 2014 at 9:22

3 Answers 3

1

You can do this using a simple Perl one-liner:

perl -i -ne 'print unless /^[,\s]*$/' <filename>

The -n flag assumes this loop around your program:

while(<>) {
   print unless /^[,\s]*$/;
}

and the -i flag means inplace and modifies your input file.

Note: If you are worried about losing your data with -i, you can specify -i.bak and perl will automatically write the original file to your <filename>.bak

Sign up to request clarification or add additional context in comments.

Comments

0

More of a command line hack,

perl -i -ne 'print if /[^,\r\n]/' file.csv

2 Comments

@user3707618 it does in-place edit. Make backup before executing.
Nice. Any way of doing something like that in a program?
0

If you want to put it inside a shell script you can do this ...

#!/bin/sh
$(perl -i -n -e 'print $_ unless  ($_ =~ /^\,+$/);' $*)

2 Comments

how could I put this in the middle of a program and make it overwrite the original file?
Is that what you are after? I'm assuming you have a script you want to add this fix to. Otherwise you could put the perl in the shebang.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.