我想做的是從一個包含一系列句子的文本檔案中加載,并創建一個陣列,其中包含每個句子作為一個單獨的索引,并帶有一些可能的 grep 條件,例如包含一個字串。這就是我得到的。它在陣列中的原因是因為我希望它稍后計算行數,但是如果它在陣列中,我可以用簡單的回圈來做,所以我想保持這種方式
#!/bin/bash
location=$(pwd)
file="${location}/text"
cat $file
string=$(cat $file |sed 's/./.*/g' | tr '*' '\n' |sed 's/?/?*/g' | tr '*' '\n' |sed 's/!/!*/g' | tr '*' '\n')
在這部分我打開了一個檔案,根據我的理解我替換了一個 . 用 .* 代替 * 用 \n 和用 ?! 做同樣的事情。所以現在我應該有一個字串,其中包含用新行分隔的每個句子
echo $string
array=( $($string | grep "hello" | grep "!") )
echo $array
現在它應該將字串放入陣列中,條件是有一個單詞 hello 并且是一個命令句。但問題是:
echo $string
otuput : . . . . . . . . . . . . etc...
還有一個創建陣列的行是說 .: .: 是一個目錄...所有代碼都沒有在下面分開
#!/bin/bash
location=$(pwd)
file="${location}/text"
cat $file
string=$(cat $file |sed 's/./.*/g' | tr '*' '\n' |sed 's/?/?*/g' | tr '*' '\n' |sed 's/!/!*/g' | tr '*' '\n')
echo $string
array=( $($string | grep "hello" | grep "!") )
echo $array
示例文本
Text text hello! hello? text text.
text text. text hello! text?
hello! text text.
預期產出:
echo $string :
Text text hello!
hello?
text text.
text text.
text hello!
text?
hello!
text text.
基本上每行一個句子(有時是開頭的空格,但沒關系),因為 string=$(cat $file |sed 's/./. /g' | tr ' ' '\n' |sed 's /?/? /g' | tr ' ' '\n' |sed 's/!/! /g' | tr ' ' '\n') 應該是這樣,但是 echo $string 的當前輸出:
Text text hello! hello? text text. text text. text hello! text? hello! text text.
至于 echo $array
basically the same as $string but each line as separate index in array
但當前輸出看起來與 $string 相同,將其列印為一個字串而不是換行中的每個句子
Please keep it within simple level, i just stared bash and created this script to learn and have fun, I know there are some incredible people using it, but from what I've seen it can get relay crazy fast :)
uj5u.com熱心網友回復:
關于echo $string- 請閱讀https://mywiki.wooledge.org/Quotes和why-is-printf-better-than-echo。
這是你想要做的嗎?
$ string=$(sed 's/\([[:punct:]]\) /\1\n/g' file)
$ printf '%s\n' "$string"
Text text hello!
hello?
text text.
text text.
text hello!
text?
hello!
text text.
$ readarray -t -d$'\n' array < <(sed 's/\([[:punct:]]\) /\1\n/g' file)
$ printf '%s\n' "${array[@]}"
Text text hello!
hello?
text text.
text text.
text hello!
text?
hello!
text text.
$ declare -p array
declare -a array=([0]="Text text hello!" [1]="hello?" [2]="text text." [3]="text text." [4]="text hello!" [5]="text?" [6]="hello!" [7]="text text.")
$ string=$(sed 's/\([[:punct:]]\) /\1\n/g' file | grep 'hello!')
$ printf '%s\n' "$string"
Text text hello!
text hello!
hello!
如果您的 sed 版本不支持\n替換,則將其更改為以下任一:
sed 's/\([[:punct:]]\) /\1\'$'\n''/g' file
sed 's/\([[:punct:]]\) /\1\
/g' file
如果它不支持字符類,則獲取一個新的 sed但否則更改[[:punct:]]為[!?.]并列出括號運算式內的所有標點符號,或者將其更改為[^][ \ta-zA-Z0-9_-]并列出您不希望在括號運算式內視為標點符號的所有字符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/455238.html
上一篇:Bash'ls'不接受*通配符
