[英]bash: write first n lines of each file in subdir to new directory with same filenames
這個 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
顯示我需要的內容,但我不知道如何將 output 路由到正確的文件。
您需要使用迷你 shell 腳本來執行此操作:
支持“健全”文件名的簡單版本(無空格等)
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 \'%\')"'
#!/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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.