簡體   English   中英

Shell腳本正則表達式匹配到數組並處理每個數組元素

[英]Shell Script regex matches to array and process each array element

雖然我已經輕松地用其他語言處理了此任務,但我不知道在Shell腳本(CentOS / BASH)時要使用哪些命令

我有一些正則表達式,可以在我已讀取到變量的文件中提供許多匹配項,並希望將正則表達式匹配項放入數組以循環處理每個條目。

正則表達式我通常使用https://regexr.com/組成捕獲組,並將其扔到JS / Python / Go中以獲取數組和循環-但是在Shell Scripting中,不確定我可以使用什么。

到目前為止,我已經使用“ sed”查找所有匹配項並替換了,但不知道它是否能夠返回數組以從匹配項中循環。

使用正則表達式,在文件上運行,返回數組。 我很樂意為該任務提供Shell腳本幫助。

編輯 :基於注釋,將其放在一起(不能通過shellcheck.net使用):

#!/bin/sh
examplefile="
asset('1a/1b/1c.ext')
asset('2a/2b/2c.ext')
asset('3a/3b/3c.ext')
"
examplearr=($(sed 'asset\((.*)\)' $examplefile))
for el in ${!examplearr[*]}
  do
    echo "${examplearr[$el]}"
  done

這在Mac上的bash中有效:

#!/bin/sh
examplefile="
asset('1a/1b/1c.ext')
asset('2a/2b/2c.ext')
asset('3a/3b/3c.ext')
"
examplearr=(`echo "$examplefile" | sed -e '/.*/s/asset(\(.*\))/\1/'`)
for el in ${examplearr[*]}; do
  echo "$el"
done

輸出:

'1a/1b/1c.ext'
'2a/2b/2c.ext'
'3a/3b/3c.ext'

請注意$ examplefile用引號引起來,並使用sed用匹配項替換整行。 如果文件中還有其他內容,可以在與“資產”字符串相同的行上,也可以在完全沒有資產的其他行中進行如下修改:

#!/bin/sh
examplefile="
fooasset('1a/1b/1c.ext')
asset('2a/2b/2c.ext')bar
foobar
fooasset('3a/3b/3c.ext')bar
"
examplearr=(`echo "$examplefile" | grep asset | sed -e '/.*/s/^.*asset(\(.*\)).*$/\1/'`)
for el in ${examplearr[*]}; do
  echo "$el"
done

並達到相同的結果。

有幾種方法可以做到這一點。 我會使用與Perl兼容的正則表達式的GNU grep(啊,令人愉悅的行噪音):

mapfile -t examplearr < <(grep -oP '(?<=[(]).*?(?=[)])' <<<"$examplefile")
for i in "${!examplearr[@]}"; do printf "%d\t%s\n" $i "${examplearr[i]}"; done
0   '1a/1b/1c.ext'
1   '2a/2b/2c.ext'
2   '3a/3b/3c.ext'

這使用bash mapfile命令從stdin讀取行並將它們分配給數組。


sed命令中缺少的位:

  • $ examplefile是文本,而不是文件名,因此您必須發送到sed的stdin
  • sed是一種有趣的小語言,帶有1個字符的命令:您已經給它指定了“ a”命令,在這種情況下是不合適的。
  • 您只需要輸出匹配項的捕獲部分,而不是每行,因此需要-n選項,並且需要在某處打印: s///pp標志表示“如果替換則打印[line]被制造”。
sed -n 's/asset\(([^)]*)\)/\1/p' <<<"$examplefile"
# or
echo "$examplefile" | sed -n 's/asset\(([^)]*)\)/\1/p'

請注意,這會返回('1a/1b/1c.ext') -並帶有括號。 如果您不想要它們,請在sed中添加-r-E選項:除其他外,這會顛倒(\\(

暫無
暫無

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

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