软著代码自动提取,并生成代码文件

更新日期: 2022-04-08 阅读次数: 5124 字数: 225 分类: Shell

申请软著需要提交 60 页代码,或者 3000 行代码。手动一个文件一个文件的复制黏贴太麻烦了。 特别是像 Android 项目这种目录层级特别多的,完全是浪费时间。

于是写了个 shell 脚本,自动生成 txt 格式的文件,然后全部复制到 word 中即可。

以 Android Kotlin 项目为例:

shell 脚本

gen_code.sh

#!/bin/bash

set -e	# or use "set -o errexit" to quit on error.
set -x  # or use "set -o xtrace" to print the statement before you execute it.

IFS=$'\n'; set -f
for filepath in $(find ./ -name '*.xml' -or -name '*.kt'); do
	echo $(basename "$filepath")>>output.txt;
	echo "">>output.txt;
	cat $filepath>>output.txt;
	echo "">>output.txt;
	echo "">>output.txt;
done
unset IFS; set +f

添加执行权限,并执行。

chmod +x gen_code.sh
./gen_code.sh

TODO

  • 去除空白行 (是否有必要)
  • 去除注释
  • 满足 3000 行自动停止
  • 输出 XML 似乎有 bug

参考

  • https://stackoverflow.com/questions/4638874/how-to-loop-through-a-directory-recursively-to-delete-files-with-certain-extensi

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式

谈笑风生

xxi

#!/bin/bash

readonly PROJECT_PATH=$(cd "$(dirname $0)"; pwd -P)

set -e	# or use "set -o errexit" to quit on error.
set -x  # or use "set -o xtrace" to print the statement before you execute it.

dirs=()
dirs+=("machineagent/main.cpp")
dirs+=("machineagent/agent")
dirs+=("machineagent/cache")
dirs+=("machineagent/common")
dirs+=("machineagent/communication")
dirs+=("machineagent/conf")
dirs+=("machineagent/utils")

maxLines=3300

echo ""> output.txt

IFS=$'\n'; set -f
for dir in ${dirs[@]}; do
    for filepath in $(find ${PROJECT_PATH}/${dir} -name '*.h' -or -name '*.cpp'); do
        echo $(basename "$filepath")>>output.txt;
        echo "">>output.txt;
        cat $filepath | grep -v "^//" >> output.txt;
        echo "">>output.txt;
        echo "">>output.txt;

        lines=$(wc -l output.txt)
        if [ ${lines} -gt ${maxLines} ]; then
            break
        fi
    done
    lines=$(wc -l output.txt)
    if [ ${lines} -gt ${maxLines} ]; then
        break
    fi
done
unset IFS; set +f