将多个字符串写入标准输出并分别通过管道传输
Write multiple strings to stdout and pipe them separately
是否可以将每个写入标准输出的字符串通过管道传输到另一个命令?
// file example.js
#!/usr/bin/env node
process.stdout.write('foo')
process.stdout.write('bar')
当我运行 ./example.js | wc -m
我得到6时,foo
和bar
的字符长度值加在一起。
我想分别获取值 3 和 3。我是否必须在我的 javascript 文件中做一些特殊的事情?还是命令?
wc -m 计算其输入中的字符数。您不能按行(或与此相关的任何其他分组)使它成为 separate/group。这与您的JS代码无关。
如果想通过其他方式获取计数的类型,用node其实也不难!
既然你提到你的内容可能是一个包含空格和行的文件,假设你需要每个文件的字符数
//example.js
#!/usr/bin/env node
process.stdout.write('foo')
process.stdout.write('~') // print any delimiter which is not part of your files content
process.stdout.write('bar')
//Split them using awk and count it as usual
./example.js | awk 'BEGIN { RS="~" } {print}' | wc -m
3
3
//or just using awk by removing spaces
./example.js | awk 'BEGIN { RS="~" } {gsub(" ", "", [=10=]); print length}'
希望对您有所帮助
是否可以将每个写入标准输出的字符串通过管道传输到另一个命令?
// file example.js
#!/usr/bin/env node
process.stdout.write('foo')
process.stdout.write('bar')
当我运行 ./example.js | wc -m
我得到6时,foo
和bar
的字符长度值加在一起。
我想分别获取值 3 和 3。我是否必须在我的 javascript 文件中做一些特殊的事情?还是命令?
wc -m 计算其输入中的字符数。您不能按行(或与此相关的任何其他分组)使它成为 separate/group。这与您的JS代码无关。
如果想通过其他方式获取计数的类型,用node其实也不难!
既然你提到你的内容可能是一个包含空格和行的文件,假设你需要每个文件的字符数
//example.js
#!/usr/bin/env node
process.stdout.write('foo')
process.stdout.write('~') // print any delimiter which is not part of your files content
process.stdout.write('bar')
//Split them using awk and count it as usual
./example.js | awk 'BEGIN { RS="~" } {print}' | wc -m
3
3
//or just using awk by removing spaces
./example.js | awk 'BEGIN { RS="~" } {gsub(" ", "", [=10=]); print length}'
希望对您有所帮助