简体   繁体   English

单行命令从bash中的文件中复制

[英]Single line command to multiply from a file in bash

As the title suggest, but is it possible to multiply two numbers together by reading in from a file using arithmetic expansion using only the commands echo or cat ? 如标题所示,但是是否可以通过仅使用echocat命令使用算术扩展从文件中读取来将两个数字相乘? i know you can do this through piping with the use of bc but i was looking to do something a little different. 我知道您可以通过使用bc管道来做到这一点,但我一直在做一些不同的事情。 So say we have a text file 所以说我们有一个文本文件

Text File 文本文件

12*9
2*3

and using cat multiply.txt | bc 和使用cat multiply.txt | bc cat multiply.txt | bc but changing it so that it doesnt require the use of bc but instead reads in the file and does the math on its own without the use of bc and with the use of arithmetic expansion instead? cat multiply.txt | bc但对其进行了更改,以使其不需要使用bc ,而是读取了文件,并且在不使用bc且使用算术扩展的情况下自行进行了数学运算吗?

You don't need cat either 你也不需要cat

for a in $(< test.txt); do echo "$(($a))" ; done

or 要么

while read -r a; do echo "$(($a))"; done < test.txt

which would handle better spaces and other chars in the file 这样可以处理文件中更好的空格和其他字符

It can be done like this (later learned it's not the right way , read comments below) 可以这样做(后来知道这不是正确的方法 ,请阅读下面的评论)

for a in $(cat test.txt); do echo "$(($a))" ; done

Result: 结果:

108
6

With only cat and echo it could be done like this but the number of lines in the file should be known beforehand and the array creation could fail for the same reason the for could. 由于只有catecho它可以这样做,但在文件中的行数应事先已知和数组创建可能会失败出于同样的原因在for可能。

a=( $(cat test.txt) ); echo "$((${a[0]}))" ; echo "$((${a[1]}))"

108
6

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

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