我有一个简单的文本,我想过滤它,然后选择每行的第二部分,然后将它们保存到单独的变量,我是shell脚本的新手。我在Windows上使用GitBash谢谢
的text.txt
mytext `one or a`
mytext `two or b or bb`
mytext `three or c`
脚本
列表= grep "mytext" text.txt
这是输出
echo "$list"
mytext `one or a`
mytext `two or b or bb
mytext `three or c`
所以我想将每行的第二部分保存到单独的变量中,例如:
echo $var01
`one or a`
echo $var02
`two or b or bb`
听起来像一个shell循环将完成这项工作:
words=()
while read -r first rest; do
[ "$first" = mytext ] || continue
words+=( "$rest" )
done < file
这将留下以下内容(使用printf
在单独的行上打印):
$ printf '%s\n' "${words[@]}"
`one or a`
`two or b or bb`
`three or c`
您可以使用awk
从输入文件中提取第二部分,然后将它们存储在bash数组中:
#!/bin/bash
# declare array "WORDS"
declare -a WORDS
INDEX=0
for WORD in $(awk '/mytext/ { print $2 }' text.txt) ; do
# insert $WORD into the array
WORDS[$INDEX]=$WORD
# increment counter
INDEX=$(($INDEX + 1))
done
echo "all words: ${WORDS[*]}"
echo "first word: ${WORDS[0]}"
echo "second word: ${WORDS[1]}"
echo "third word: ${WORDS[2]}"