正则表达式 – Bash:用curl结果替换数组值
我有一个名为raw.txt的文本文件,其中包含以下内容:
T DOTTY CRONO 52/50 53/40 54/30 55/20 RESNO NETKI U CYMON DENDU 51/50 52/40 53/30 54/20 DOGAL BEXET V YQX KOBEV 50/50 51/40 52/30 53/20 MALOT GISTI W VIXUN LOGSU 49/50 50/40 51/30 52/20 LIMRI XETBO X YYT NOVEP 48/50 49/40 50/30 51/20 DINIM ELSOX Y DOVEY 42/60 44/50 47/40 49/30 50/20 SOMAX ATSUR Z SOORY 43/50 46/40 48/30 49/20 BEDRA NERTU A DINIM 51/20 52/30 50/40 47/50 RONPO COLOR B SOMAX 50/20 51/30 49/40 46/50 URTAK BANCS C BEDRA 49/20 50/30 48/40 45/50 VODOR RAFIN D ETIKI 48/15 48/20 49/30 47/40 44/50 BOBTU JAROM E 46/40 43/50 42/60 DOVEY F 45/40 42/50 41/60 JOBOC G 43/40 41/50 40/60 SLATN 我正在把它读成一个数组: while read line; do set $line IFS=' ' read -a array <<< "$line" done < raw.txt 我试图用卷曲结果替换所有出现的[A-Z] {5},其中[A-Z] {5}的匹配作为变量馈入卷曲调用. 要替换的第一场比赛将是DOTTY.该调用类似于curl -s http://example.com/api_call/DOTTY,结果类似于-55.5833 50.6333,它应该替换数组中的DOTTY. 我到目前为止无法正确匹配所需的字符串并将匹配送入curl. 非常感谢您的帮助. 祝一切顺利, 编辑: 解 工作解决方案基于@Kevin广泛的答案和@Floris暗示卷曲结果中可能的回车.确实如此.谢谢!结合我身边的一些修修补补,我现在可以开始工作了. #!/bin/bash while read line; do set $line IFS=' ' read -a array <<< "$line" i=0 for str in ${array[@]}; do if [[ "$str" =~ [A-Z]{5} ]]; then curl_tmp=$(curl -s http://example.com/api_call/$str) # cut off line break curl=${curl_tmp/$'r'} # insert at given index declare array[$i]="$curl" fi let i++ done # write to file for index in "${array[@]}"; do echo $index done >> $WORK_DIR/nats.txt done < raw.txt 解决方法
我没有改变你的脚本,除了添加匹配的部分,因为它似乎是你需要帮助的:
#!/bin/bash while read line; do set $line IFS=' ' read -a array <<< "$line" for str in ${array[@]}; do if [[ "$str" =~ [A-Z]{5} ]]; then echo curl "http://example.com/api_call/$str" fi done done < raw.txt 编辑:添加在您提供URI中的变量的url示例中.通过将其更改为do_something“$(curl …)”,您可以使用获取的输出执行任何操作 编辑2:既然你想要维护你从每一行创建的bash数组,那么这个怎么样: 当谈到阵列时我对bash并不擅长,所以我希望有人给我打电话,但这应该有效. 我在那里留下了一些回声,所以你可以看到它在做什么. shift命令用于在正则表达式匹配时从当前位置推送数组索引.用于保存curl输出的tmp变量可能会得到改善,但我希望这可以让你开始. removed temporarily to avoid confusion 编辑3:哎呀上面没有实际工作.我的错.让我再试一次. EDIT4: #!/bin/bash while read line; do set $line IFS=' ' read -a array <<< "$line" i=0 # echo ${array[@]} below is just so you can see it before processing. You can remove this echo "Array before processing: ${array[@]}" for str in ${array[@]}; do if [[ "$str" =~ [A-Z]{5} ]]; then # replace the echo command below with your curl command # ie - curl="$(curl http://example.com/api_call/$str)" curl="$(echo 1234 -1234)" if [[ "$flag" = "1" ]]; then array=( ${adjustedArray[@]} ) push=$(( $push + 2 )); let i++ else push=1 fi adjustedArray=( ${array[@]:0:$i} ${curl[@]} ${array[@]:$(( $i + $push)):${#array[@]}} ) #echo "DEBUG adjustedArray in loop: ${adjustedArray[@]}" flag=1; fi let i++ done unset flag echo "final: ${adjustedArray[@]}" # do further processing here done < raw.txt 我知道有一种更聪明的方法可以做到这一点,但我们正在进入bash领域我不太适合提供建议.以上应该有效,但我希望有人可以做得更好. 无论如何,希望它有所帮助 ps – 你可能不应该使用shell脚本,除非你真的需要. Perl,php或python会使代码变得简单易读 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |