【问题标题】:bash: write first n lines of each file in subdir to new directory with same filenamesbash:将子目录中每个文件的前 n 行写入具有相同文件名的新目录
【发布时间】:2020-07-21 23:33:50
【问题描述】:

这个 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 

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

【问题讨论】:

  • 绝对有可能,for f in src_dist/* ; do sed -n '1,10p' "$f" > otherDir/"$f".hdr ; done 之类的东西会让你开始。如果您卡在bash 解决方案上,请发布新的 Q。确保在弄清楚这一点时设置一个测试目录结构。很容易弄乱你的核心文件。祝你好运。

标签: bash xargs


【解决方案1】:

您需要检测一个 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 \'%\')"'

【讨论】:

【解决方案2】:
#!/bin/sh

next() {
[[ -s stack ]] && main
end
}

main() {
line=$(ed -s stack < edprint+.txt)
head -10 "${line}" > ./newdir/newfile
ed -s stack < edpop+.txt
next
}

end() {
rm -v ./stack
rm -v ./edprint+.txt
rm -v ./edpop+.txt
exit 0
}

find . -type -f > stack

cat >> edprint+.txt << EOF
1
q
EOF

cat >> edpop+.txt << EOF
1d
wq
EOF

next

【讨论】:

    猜你喜欢
    • 2020-04-11
    • 2015-03-01
    • 2013-11-18
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    相关资源
    最近更新 更多