簡體   English   中英

如何從二進制文件中刪除起始換行符或起始新行?

[英]How to remove starting newlines or the starting new from a binary file?

我看到有關於刪除尾隨換行符的討論。

如果換行符是文件中的最后一個字符,如何刪除換行符?

但我沒有找到關於刪除起始換行符的討論。 任何人都可以讓我知道刪除起始換行符的最佳方法是什么(首選一個班輪)? 謝謝。

chomp的等效相反 Perl 代碼是s/^\\n// 與其在最后一行 (eof) 上做,不如在第一行做。 即使它只是一個空行,刪除換行符也意味着該行不會在輸出中打印任何內容。

perl -pe 's/^\n// if $. == 1' filename >filename2

或就地:

perl -pi -e 's/^\n// if $. == 1' filename

由於起始換行符定義為空行,因此您也可以使用-n而不是-p跳過打印它們(相同的行為但不打印,因此您可以確定要打印哪些行)。

perl -ni -e 'print unless $. == 1 and m/^\n/' filename

如果您想刪除潛在的多個起始換行符,您可以采用另一種方法; 在開始時自己推進手柄,直到您收到一條非空行。

perl -pi -e 'if ($. == 1) { $_ = <> while m/^\n/ }' filename

如果您不介意一次將整個文件讀入內存而不是逐行讀取,這一切都會容易得多:

perl -0777 -pi -e 's/^\n+//' filename

為了避免在編輯文件時做任何多余的工作,除非它以換行符開頭,您可以通過在它前面加上另一個命令來調節編輯條件(讀取文件的第一行,如果它不是以換行符開頭,則會導致非零退出狀態)新隊):

perl -e 'exit 1 unless <> =~ m/^\n/' filename && perl ...

在 Python 中,開始讀取文件而不用循環寫入,直到獲得非空行。

outdata = ""
with open(filename) as infile:
    while True:
        line = infile.readline()
        if line != "\n":
            break
    if line:
        outdata = line # save first non-empty line
    outdata += infile.read() # save the rest of the file
with open(filename, "w") as outfile:
    outfile.write(outdata)

跳過前導空行的簡單過濾器

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

my $begin = 1;

while( <> ) {
        next if /^$/ and $begin;
        $begin = 0;
        say;
}

一個班輪版本perl -0777 -pe 's/^\\n+//' filename

這是我想出來的,我相信它仍然可以改進一點。

with open('../resources/temp_in.txt', 'r+') as file:
    overwrite = False
    for line in file:
        if line:
            overwrite = True
            first_line = line
            break
    if overwrite:
        contents = first_line + file.read()
        file.seek(0)
        file.write(contents)
        file.truncate()

這是一個替代解決方案,它打開文件兩次。

with open('../resources/temp_in.txt') as file:
    for line in file:
        if line.strip():
            contents = line + file.read()
            break
    else:
        contents = ''

with open('../resources/temp_in.txt', 'w') as file:
    file.write(contents)

當您找到不只是換行符的行時設置一個標志,並在設置該標志時打印:

awk '/./{f=1}f' file

例如:

$ printf '\n\n\nfoo\nbar\n'



foo
bar

$ printf '\n\n\nfoo\nbar\n' | awk '/./{f=1}f'
foo
bar

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM