首页 > 解决方案 > bash:将子目录中每个文件的前 n 行写入具有相同文件名的新目录

问题描述

这个python 3代码正是我想要的

from pathlib import Path
def minify(src_dir:Path, dest_dir:Path, n: int):
    """Write first n lines of each file f in src_dir to dest_dir/f"""
    dest_dir.mkdir(exist_ok=True)
    for path in src_dir.iterdir():
        new = [x.rstrip() for x in list(path.open().readlines())][:n]
        dest_path = dest_dir.joinpath(path.name)
        dest_path.open('w').write('\n'.join(new))

有没有办法在 bash 中做同样的事情,也许是xargs

ls src_dist/* | xargs head -10 

显示我需要的内容,但我不知道如何将该输出路由到正确的文件。

标签: bashxargs

解决方案


您需要检测一个 mini shell scriptlet 来执行此操作:

支持“健全”文件名的简单版本(无空格等)

ls src_dist/* | xargs -I% bash -c 'head -10 % > dst_dir/$(basename %)'

更复杂的 CLI,支持例如带空格的文件名:

find src_dist/* -maxdepth 1 -type f -print0 | xargs -0 -I% bash -c $'head -10 "%" > "dst_dir/$(basename \'%\')"'

推荐阅读