/ / grepを抽出してbash配列に分割する方法 - linux、bash、shell、sh

どのようにgrepを抽出し、bash配列にカットするか - linux、bash、shell、sh

私は試した:

ここにfile.txtの内容です

some other text
#1.something1=kjfk
#2.something2=dfkjdk
#3.something3=3232
some other text

bashスクリプト:

ids=( `grep "something" file.txt | cut -d"." -f1` )

for id in "${ids[@]}"; do
echo $id
done

結果:

(nothing newline...)
(nothing newline...)
(nothing newline...)

しかし、それはすべてのそのようなIDのための改行のような何も私は行方不明です見つけた何もプリントされていません?

回答:

回答№1は1

きみの grep そして cut 動作しているはずですが、使用することができます awk 2つのコマンドを1つに減らします。

while read -r id;
echo "$id"
done < <(awk -F "\." "/something/{print $1}" file.txt)

配列に値を設定するには:

ids=()
while read -r id;
ids+=( "$id" )
done < <(awk -F "\." "/something/{print $1}" file.txt)

回答№2の場合は1

あなたは使うことができます grep"s -o 正規表現にマッチしたテキストのみを出力するオプション:

$ ids=($(grep -Eo "^#[0-9]+" file.txt))
$ echo ${ids[@]}
#1 #2 #3

これは、もちろん、ライン上にピリオドが存在するかどうかをチェックしません。それが重要であれば、別のパイプで物事を拡張することもできます。

$ ids=($(grep -Eo "^#[0-9]+.something" file.txt | grep -o "^#[0-9]*"))

配列を作成した後に配列値をトリミングすることもできます。

$ ids=($(grep -Eo "^#[0-9]+.something" file.txt))
$ echo ${ids[@]}
#1.something #2.something #3.something
$ for key in "${!ids[@]}"; do ids[key]="${ids[key]%.*}"; done
$ echo ${ids[@]}
#1 #2 #3