2015-06-02 37 views
1

我有一個5000000行的文本文件,我想從每個1000中提取一行並將它們寫入新的文本文件。新的文本文件應該是5000行。從shell腳本中的文件中提取行

你能幫我嗎?

+2

哪個Shell?你有什麼嘗試? –

+0

哪一行,第一個還是最後一個? – kenorb

+0

請顯示您的工作。 – muglio

回答

-1

您可以使用headtail,取決於您想要提取哪一行。

從每個文件中提取第一行(例如*.txt文件):

head -n1 *.txt | grep -ve ^= -e ^$ > first.txt 

爲了從每個文件的最後一行,只需使用tail,而不是head

要提取特定行,請參閱:How do I use Head and Tail to print specific lines of a file

0

我會使用python腳本來做到這一點。但是,您的shell也可以使用相同的邏輯。這是python代碼。

input_file = 'path/file.txt' 
output_file = 'path/output.txt' 
n = 0 

with open(input_file, 'r') as f: 
    with ope(output_file, 'w') as o: 
     for line in f: 
      n += 1 
      if n == 1000: 
       o.write(line) 
       n = 0 

基本上,你初始化一個計數器,那麼你迭代通過行的文件行,你增加計數器的每一行,如果計數器打1000你寫在新文件中的行並重置計數器回來。

Here是如何使用Bash shell遍歷文件的行。

相關問題