bash - 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
显示我需要的内容,但我不知道如何将该输出路由到正确的文件。
解决方案
您需要检测一个 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 \'%\')"'
推荐阅读
- html - 正则表达式匹配 HTML 和非 HTML URL
- algorithm - 用于生成此表中数字的算法是什么,N = 6 的输出是什么?
- css - 如何使用伪元素隐藏img标签
- c - 如何在 BST 中找到小于或等于给定值的节点数?(AVL 树)
- c - 比较函数在 qsort 中给出分段错误
- sql - 修剪列内的额外空白
- arrays - 将项目添加到猫鼬引用对象数组时出现问题
- ruby-on-rails - ERB `each_with_index` 中的模运算符
- c# - 将文件数组从 Jquery ajax 发送到控制器操作
- laravel - Laravel cors 无法在 Apache 服务器上运行