简体   繁体   English

为什么“ sh -c”返回与实际命令不同的结果?

[英]Why is 'sh -c' returning a different result from my actual command?

I'm trying to get the number of pages in a PDF file through the command line. 我正在尝试通过命令行获取PDF文件中的页数。

pdfinfo "/tmp/temp.pdf" | grep Pages: | awk '{print $2}'

produces 产生

3

In Node.js, I need to use 'sh' because of the piping. 在Node.js中,由于管道问题,我需要使用“ sh”。

But

sh -c "pdfinfo '/tmp/temp.pdf' | grep Pages: | awk '{print $2}'"

produces 产生

Pages:          3

Why am I getting different output? 为什么我得到不同的输出?

The sh -c command is double quoted, which will expand the $2 which is likely empty, so the awk command becomes just print which prints the whole line. sh -c命令用双引号引起来,这将扩展$2 ,该$2可能为空,因此awk命令变为print ,它会打印整行。 You could escape the $ to prevent it from being expanded: 您可以转义$以防止其扩展:

sh -c "pdfinfo '/tmp/temp.pdf' | grep Pages: | awk '{print \$2}'"

Incidentally, awk can do pattern matching, so no need for both grep and awk : 顺便说一句, awk可以进行模式匹配,因此不需要grepawk

pdfinfo "/tmp/temp.pdf" | awk '/Pages:/ {print $2}'

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

相关问题 为什么循环中的Mongoose查询仅返回第一个结果? - Why is my Mongoose query within a loop only returning the first result? 为什么我的 mongoose findOne 查询返回多个结果 - why is my mongoose findOne query returning more than one result 为什么我的递归函数不返回最终结果? - Why isn't my recursive function returning the final result? 为什么我的间隔基于推送到数组会返回不同的结果? - Why is my interval returning different results based on pushing to an array? 为什么当我看到结果在我的数据库中时,sequelize.findOne()没有返回结果 - Why sequelize.findOne() is not returning the result while I can see the result is in my DB 为什么 NodeJs req.get('host') 结果到数字海洋上的 localhost:3000 而不是我的实际域名 - Why does NodeJs req.get('host') result to localhost:3000 on digital ocean instead of my actual domain name Dockerfile ..... ✖ 错误:命令失败:/bin/sh -c autoreconf -ivf /bin/sh: autoreconf: not found - Dockerfile ..... ✖ Error: Command failed: /bin/sh -c autoreconf -ivf /bin/sh: autoreconf: not found 为什么req.socket.address()。address显示的IP地址与实际的公共IP地址不同? - Why does req.socket.address().address show a different IP address than my actual public IP address? 有效负载字节与实际字节不同 - Payload bytes different from actual bytes nodejs 从函数返回结果 - nodejs returning result from functions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM