[英]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.