如何通过shell脚本将特定字符保存到变量中

时间:2018-03-01 12:28:56

标签: bash shell powershell

我有一个简单的文本,我想过滤它,然后选择每行的第二部分,然后将它们保存到单独的变量,我是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` 

2 个答案:

答案 0 :(得分:1)

听起来像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`

答案 1 :(得分:0)

您可以使用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]}"
相关问题