繁体   English   中英

如何有效地从 Bash 中具有所述函数名称的文件和前缀文件中读取函数名称?

[英]How to read function names from file and prefix file with said function names in Bash effectively?

我有一堆文件,我将它们连接成一个大文件。 单个大文件如下所示:

function foo() {
  // ... implementation
}

function bar() {
  // ... implementation
}

function baz() {
  // ... implementation
}

function foo_bar() {
  // ... implementation
}

...

一堆功能。 我想用所有这些内容创建一个新文件,加上它的前缀:

module.exports = {
  foo,
  bar,
  baz,
  foo_bar,
  ...
}

基本上导出每个功能。 我可以在 bash 中执行此操作的最简单、最干净的方法是什么?

据我所知,这是哈哈,尝试提出解决方案真的很令人困惑:

A := out/a.js
B := out/b.js

all: $(A) $(B)

$(A):
  @find src -name '*.js' -exec cat {} + > $@

$(B):
  @cat out/a.js | grep -oP '(?function )[a-zA-Z0-9_]+(? \{)'

.PHONY: all

这个简单的awk脚本可以做到

awk -F '( |\\()' 'BEGIN {print "module.exports = {"} /function/ {print "\t" $2 ","} END {print "}"}' largefile.js

存储在获取文件之前和之后声明的函数列表。 计算差异。 您可以使用declare -F获取当前声明的函数列表。

A() { :; }
pre=$(declare -F | sed 's/^declare -f //')

function foo() {
  // ... implementation
}

function bar() {
  // ... implementation
}

function baz() {
  // ... implementation
}

function foo_bar() {
  // ... implementation
}

post=$(declare -F | sed 's/^declare -f //')

diff=$(comm -13 <(sort <<<"$pre") <(sort <<<"$post"))

echo "module.exports = {
    $(<<<"$diff" paste -sd, | sed 's/,/,\n\t/g')
}"

我认为使用bash --norc你应该得到一个干净的环境,所以使用bash --norc -c 'source yourfile.txt; declare -F' bash --norc -c 'source yourfile.txt; declare -F'你可以计算差异:

cat <<EOF >yourfile.txt
function foo() {
  // ... implementation
}

function bar() {
  // ... implementation
}

function baz() {
  // ... implementation
}

function foo_bar() {
  // ... implementation
}
EOF

diff=$(bash --norc -c 'source yourfile.txt; declare -F' | cut -d' ' -f3-)

echo "module.exports = {
    $(<<<"$diff" paste -sd, | sed 's/,/,\n\t/g')
}"

两个代码片段都应该输出:

module.exports = {
    bar,
    baz,
    foo,
    foo_bar
}

注意: function name() {}是函数定义的 ksh 和 posix 形式的混合 - ksh 使用function name {}而 posix 使用name() {} Bash 支持两种形式以及两种形式的奇怪组合。 为了便于移植,只需使用 posix 版本name() {} 更多信息可能在wiki-deb-bash-hackers.org obsolete and deprecated syntax

您可以使用echosed

echo 'modules.exports = {'; sed -n 's/^function \([^(]*\)(.*/  \1,/p' input.txt; echo '}'

结果:

modules.exports = {
  foo,
  bar,
  baz,
  foo_bar,
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM