BASH sed不评估数组

时间:2016-03-17 03:25:33

标签: bash

所以我有一个带文件名的数组。

for i in "${!array_FILE[@]}"; do 
  printf "%s\t%s\n" "$i" "${array_FILE[$i]}"
  sed -e "s/\${USERNAME_VAR}/$USERNAME_VAR/" -e "s/\${USERNAME}/$USERNAME/" template > array_FILE[$i].js
done

printf工作并给我

0       app_calander
1       app_contacts
2       app_search
3       app_index

但创建的文件是:

array_FILE[0].js
array_FILE[1].js
array_FILE[2].js
array_FILE[3].js

而不是

app_calander.js
app_contacts.js
app_search.js
app_index.js

如果你能帮助我,我很感激,它必须由索引来改变,因为我有两个数组,我需要在同一个索引处更改值。

我的临时解决方案是:

filename="${array_FILE[$i]}"
sed -e "s/\${USERNAME_VAR}/$USERNAME_VAR/" -e "s/\${USERNAME}/$USERNAME/" template > $filename.js

但我想知道是否有更好的方法!

REAL ISSUE

现在真正的问题是我尝试传递网址

for i in "${!array_FILE[@]}"; do 
  #printf "%s\t%s\n" "$i" "${array_FILE[$i]}"
  filename="${array_FILE[$i]}"
  url="${array_URL[$i]}"
  sed -e "s/\${USERNAME_VAR}/$USERNAME_VAR/" -e "s/\${USERNAME}/$USERNAME/" -e "s/\${URL}/'$url'/" template > $filename.js
done

sed: -e expression #3, char 18: unknown option to `s'
sed: -e expression #3, char 18: unknown option to `s'
sed: -e expression #3, char 18: unknown option to `s'
sed: -e expression #3, char 18: unknown option to `s'

url的样本值为URL:https://example.com/app/index.html

编辑澄清

data.txt中

USERNAME_VAR:input_username
USERNAME:user01
PASSWORD_VAR:input_password
PASSWORD:password1
SUBMIT:submit
AUTH:cas
URL:https://example.com/app/calander.html
FILE:app_calander
URL:https://example.com/app/contacts.html
FILE:app_contacts
URL:https://example.com/app/search.html
FILE:app_search
URL:https://example.com/app/index.html
FILE:app_index

模板

${USERNAME_VAR} = ${USERNAME}
${SUBMIT} IS TRUE
${PASSWORD_VAR} = ${PASSWORD}
${AUTH} = AUTH IS
URL TO HIT IS ${URL}

inject.sh

#!/bin/bash

USERNAME_VAR=($(grep -o 'USERNAME_VAR.*' data.txt | cut -f2- -d':'))
USERNAME=($(grep -o 'USERNAME.*' data.txt | grep -v 'VAR.*' | cut -f2- -d':'))
echo $USERNAME_VAR
echo $USERNAME

array_URL=($(grep -o 'URL.*' data.txt | cut -f2- -d':'))
array_FILE=($(grep -o 'FILE.*' data.txt | cut -f2- -d':'))

for i in "${!array_FILE[@]}"; do 
  #printf "%s\t%s\n" "$i" "${array_FILE[$i]}"
  FILENAME="${array_FILE[$i]}"
  URL="${array_URL[$i]}"
  echo $URL
  sed -e "s/\${URL}/$URL/" -e "s/\${USERNAME_VAR}/$USERNAME_VAR/" -e "s/\${USERNAME}/$USERNAME/" template > $FILENAME.js
done

2 个答案:

答案 0 :(得分:0)

  1. 第一个问题的答案就是盯着你:"${array_FILE[$i]}"明显不同于"array_FILE[$i]"

  2. 要了解" REAL ISSUE",只需查看错误消息。他们告诉你问题是第三个sed表达式,它假定$ url没有" /"在它。

  3. 除非您确定$ USERNAME,$ USERNAME_VAR和$ url没有" /"在他们中,那些sed命令将无法以您期望的方式工作。

答案 1 :(得分:0)

继续发表评论,您可以执行以下操作:

for i in "${!array_FILE[@]}"; do 
    #printf "%s\t%s\n" "$i" "${array_FILE[$i]}"
    filename="${array_FILE[$i]}"
    url="${array_URL[$i]}"
    sed -e "s#\${USERNAME_VAR}#$USERNAME_VAR#" \
    -e "s#\${USERNAME}#$USERNAME#" \
    -e "s#\${URL}#$url#" template > $filename.js
done