簡體   English   中英

如何通過shell腳本將特定字符保存到變量中

[英]How to save specific character into variable by shell script

我有一個簡單的文本,我想對其進行過濾,然后選擇每行的第二部分,然后將它們保存到單獨的變量中,我是 shell 腳本的新手。 我在 Windows 上使用 GitBash 謝謝

文本文件

mytext `one or a`
mytext `two or b or bb`
mytext `three or c`

腳本

list= 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]}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM