如何提取grep并切割成bash数组

时间:2015-03-09 14:44:31

标签: 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的换行符,我发现了什么?

2 个答案:

答案 0 :(得分:1)

您的grepcut应该有效,但您可以使用awk并将2个命令合并为一个:

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)

答案 1 :(得分:1)

您可以使用grep的{​​{1}}选项仅输出正则表达式匹配的文本:

-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]*'))