PYPL
PYPL

Reputation: 1849

Perl: How to remove spaces and blank lines in one pass

I have got 2 perl scripts, first one removes blank lins from a file and the second one removes all spaces inside a file. I wonder, if it's possible to connect both of these regular expressions inside 1 script?


For spaces, i have used this regsub: $str =~ tr/ //d; and for Blank lines, I have used this regexp

while (<$file>) {
    if (/\S/){
    print $new_file $_; }}

Upvotes: 1

Views: 8833

Answers (2)

user2677944
user2677944

Reputation: 127

If you wish to trim the end of the line that contains space, you might want it to work like this:

perl -pi -e 's/\s*$/\n/' f1 f2 f3   #UNIX file format
perl -pi -e 's/\s*$/\r\n/' f1 f2 f3   #DOS file format

Upvotes: 2

choroba
choroba

Reputation: 241768

It should be really easy: just add tr/ //d before the if line.

Note: It will remove lines containing spaces only, too. If you want to keep them (but transliterated to empty lines), insert the transliteration before the print line.

Upvotes: 4

Related Questions