获取目录中每个文件的“头”?

问题描述 投票:0回答:4

我正在处理大文件,我的问题有两个。

  1. Bash - 出于测试目的,我想迭代给定目录中的每个文件,获取每个文件的

    Head
    (比如
    Head
    10000
    ),并留下每个文件的精简版本。要么在 同一目录或另一个目录并不重要,尽管我 假设同样的会是首选。

  2. Python3 - 如何以编程方式执行此操作?我想我需要使用 os 模块

linux bash ubuntu python-3.x
4个回答
5
投票

使用 尝试一下:

for i in *; do
    cp "$i" "$i.tail"
    sed -i '10001,$d' "$i.tail"
done

或者简单地:

for i in *; do
    sed '10001,$d' "$i" > "$i.tail"
done

或:

for i in *; do
    head -n 1000 "$i" > "$i.tail"
done

对于 python,如果您想使用 shell 代码,请参阅 http://docs.python.org/2/library/subprocess.html


5
投票

重击:

最直接的方法:

#!/usr/bin/env bash
DEST=/tmp/
for i in *
do
   head -1000 "${i}" > ${DEST}/${i}
done

如果您有大量文件,您可以通过生成文件列表、将它们拆分并针对每个列表运行循环来运行多个作业。

Python:

假设目标是不生成 shell 会话来执行外部二进制文件,例如“head”,这就是我的做法。

#!/usr/bin/env python
import os

destination="/tmp/"

for file in os.listdir('.'):
  if os.path.isfile( file ):
    readFileHandle = open(file, "r")
    writeFileHandle = open( destination + file , "w")
    for line in range( 0,1000):
      writeFileHandle.write(readFileHandle.readline())
    writeFileHandle.close()
    readFileHandle.close()

0
投票

怎么样:

ls | xargs -i head {}

-1
投票

要以这种方式缩写当前目录中的所有文件,您可以使用:

for f in *; do [[ $f != *.small ]] && head -n 10000 "$f" > "$f".small; done

文件将以

.small
为后缀。

要从 python 中执行此操作,

import os
os.system('for f in *; do [[ $f != *.small ]] && head -n 10000 "$f" > "$f".small; done')
© www.soinside.com 2019 - 2024. All rights reserved.