Nicolas El Khoury
Nicolas El Khoury

Reputation: 6527

Unable to replace string using sed

I have a bash script that loops over a set of files, and replaces a string, in each file, with a version number.

#!/bin/bash

ANGULAR_APP_VERSION=6.6.6
echo $ANGULAR_APP_VERSION

declare -a arr=(
"test1.txt" 
"test2.txt"
)

for i in "${arr[@]}"
do
  sed 's/"@@BUILD_VERSION@@"/"'$ANGULAR_APP_VERSION'"/g' ${arr[$i]}
done

Everytime I run the script, it generates the following error:

./test1.txt: syntax error: operand expected (error token is "./test1.txt")

I don't understand why it is wrong. The files exist.

Upvotes: 1

Views: 145

Answers (1)

Gilles Quénot
Gilles Quénot

Reputation: 185831

#!/bin/bash

ANGULAR_APP_VERSION="6.6.6"
echo "$ANGULAR_APP_VERSION"

arr=(
    "test1.txt" 
    "test2.txt"
)

for i in "${arr[@]}"; do
     sed -i "s/@@BUILD_VERSION@@/$ANGULAR_APP_VERSION/g" "$i"
done

($i is each value of the array one at a time in the iteration)

or using array key :

for i in "${!arr[@]}"; do
     sed -i "s/@@BUILD_VERSION@@/$ANGULAR_APP_VERSION/g" "${arr[i]}"
done

Learn how to quote properly in shell, it's very important :

"Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words

Upvotes: 3

Related Questions