簡體   English   中英

如何使用awk讀取每n個字符而不是每行的文件?

[英]How to read a file each n characters instead of each line using awk?

這是file.txt的內容:

hello bro
my nam§
is Jhon Does

該文件還可以包含不可打印的字符(例如\\ x00或\\ x02) ,並且,如您所見,行的長度不相同。

然后,我想每5個字符讀取一次,而不必換行。 我想用awk這樣的事情:

awk -v RS='' '{
  s=s $0;
}END{
  n=length(s);

  for(x=1; x<n; x=x+5){
    # Here I will put some calcs and stuff

    i++;
    print "line " i ": #" substr(s,x,5) "#"
  }
}' file.txt

輸出如下:

line 1: #hello#
line 2: # bro
#
line 3: #my na#
line 4: #m§
is#
line 5: # Jhon#
line 6: # Does#

它可以完美運行,但是輸入文件將非常大,因此性能很重要。

簡而言之,我正在尋找這樣的東西:

awk -v RS='.{5}' '{ # Here I will put some calcs and stuff }'

但這是行不通的。

另一個可行的選擇:

xxd -ps mifile.txt | tr -d '\n' | fold -w 10 | awk '{print "23" $0 "230a"}' | xxd -ps -r

你有什么想法或選擇嗎? 謝謝。

假設您使用的是普通字符,則可以使用perl和binmode。

use strict;
use warnings;

open my $fh, '<', 'test'; 
#open the file.
binmode $fh;
# Set to binary mode
$/ = \5;
#Read a record as 5 bytes

while(<$fh>){
#Read records
        print "$_#"
        #Do whatever calculations you want here
}

對於擴展字符集,可以使用UTF8並每5個字符而不是字節讀取一次。

use strict;
use warnings;

open my $fh, '<:utf8', 'test';
#open file in utf8.
binmode(STDOUT, ":utf8");
# Set stdout to utf8 as well

while ((read($fh, my $data, 5)) != 0){
#Read 5 characters into variable data
    print "$data#";
    #Do whatever you want with data here
}

如果您對Python沒問題 ,可以嘗試一下

f = open('filename', 'r+')
w = f.read(5)
while(w != ''):
        print w;
        w = f.read(5);
f.close()

因此,您問如何使用awk而不是每行讀取n個字符的文件。

解決方案

如果您有現代的gawk實現,請使用FPAT

通常,當使用FS時,gawk會將字段定義為記錄的一部分,出現在每個字段分隔符之間。 換句話說,FS定義了什么不是字段,而不是什么字段。 但是, 有時您確實想根據字段的定義而不是不是字段的定義

碼:

gawk 'BEGIN{FS="\n";RS="";FPAT=".{,5}"}
            {for (i=1;i<=NF;i++){
               printf("$%d = <%s>\n", i, $i)}
            }' file

檢查演示

我不確定我是否了解您想要的內容,但這與您問題中的腳本的輸出相同,您說的很完美,因此希望是這樣:

$ awk -v RS='.{5}' 'RT!=""{ print "line", NR ": #" RT "#" }' file
line 1: #hello#
line 2: # bro
#
line 3: #my na#
line 4: #m§
is#
line 5: # Jhon#
line 6: # Does#

上面使用GNU awk進行多字符RS和RT。

暫無
暫無

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

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