写了个bash函数把文件内容分成几段并格式化方便粘贴到copilot

用法 ls *.py | batch_split_for_copilot,结果输出到"$HOME/.my_code_file.md".

代码,

batch_split_for_copilot () 
{ 
    local lines_per_chunk="${1:-100}";
    local output="$HOME/.my_code_file.md";
    rm -f "$output";
    while IFS= read -r file; do
        if [ ! -f "$file" ]; then
            echo "Skipping: file not found — $file" 1>&2;
            continue;
        fi;
        local filename="$(basename "$file")";
        local extension="${filename##*.}";
        local total_lines;
        total_lines=$(wc -l < "$file");
        local chunks=$(( (total_lines + lines_per_chunk - 1) / lines_per_chunk ));
        local lang="text";
        case "$extension" in 
            py)
                lang="python"
            ;;
            sh)
                lang="bash"
            ;;
            c)
                lang="c"
            ;;
            cpp)
                lang="cpp"
            ;;
            js)
                lang="javascript"
            ;;
            html)
                lang="html"
            ;;
            md)
                lang="markdown"
            ;;
            rb)
                lang="ruby"
            ;;
            go)
                lang="go"
            ;;
            rs)
                lang="rust"
            ;;
            java)
                lang="java"
            ;;
            ts)
                lang="typescript"
            ;;
            css)
                lang="css"
            ;;
            json)
                lang="json"
            ;;
            yml | yaml)
                lang="yaml"
            ;;
        esac;
        for ((i=0; i<chunks; i++))
        do
            local start=$((i * lines_per_chunk + 1));
            local end=$((start + lines_per_chunk - 1));
            local header="### Part $((i+1)) of $chunks — \`$filename\` lines $start to $end";
            echo -e "$header\n" >> "$output";
            echo "\`\`\`$lang" >> "$output";
            sed -n "${start},${end}p" "$file" >> "$output";
            echo "\`\`\`" >> "$output";
            echo -e "\n---\n" >> "$output";
        done;
    done;
    echo "Markdown output saved to: $output"
}
1 个赞