簡體   English   中英

使用bash腳本從文件讀取元素

[英]Read Elements from file using bash script

如果我有一個名稱為“ read7”的文件,其中包含數字列表,例如:

2
3
4

如何編寫帶有while循環的bash腳本,以讀取文件中的所有元素並對數字求平方並將其作為標准輸出發送?

因此,在運行腳本之后,我們應該獲得輸出

4
9
16

試試awk:

awk '{print $1*$1}' read7

您不需要使用while循環。 使用awk

$ cat read7
2
3
4
$ awk '{print $1*$1}' read7
4
9
16

如果要使用while循環,可以說:

while read -r i; do echo $((i*i)); done < read7

對於您的輸入,它將發出:

4
9
16

根據您的注釋if the file has words and numbers in it. How do I make it read just the numbers from the file? if the file has words and numbers in it. How do I make it read just the numbers from the file? 你可以說:

while read -r i; do [[ $i == [0-9]* ]] && echo $((i*i)); done < read7

對於包含以下內容的輸入文件:

2
foo
3
4

它會產生:

4
9
16

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM