Sed find replace using bash arrays not working

I have three files, two files with 2259 IP addresses in each file. One file since 137772. The script uses sed with bash arrays and a for loop to replace the IP addresses in access.log with different IP addresses. After several hours of work, the script fails to execute this error:

sed: -e expression # 1, char 0: no previous regular expression

The number of uniq IP addresses is also limited to six IP addresses.

Here is the script:

#!/bin/bash
_ORGIFS=$IFS
IFS=$'\n'
_alIPs=($(<access.log.IPs)
_fIPs=($(<randomIPs.txt)
for (( _i=1; _i<=2259; _i++ ))
do 
  sed -i "s/${_alIPs[$_i]}/${_fIPs[$_i]}/g" access.log
done
IFS=$_ORGIFS
0
source share
2 answers

An array exponent in bash starts at 0. When you say

for (( _i=1; _i<=2259; _i++ ))

you ignore the first entry and go past the end, after which

sed -i "s/${_alIPs[$_i]}/${_fIPs[$_i]}/g" access.log

expands to

sed -i "s//something/g" access.log

// s , , .

for (( _i=0; _i<2259; _i++ ))

... , , , .

:

sed -i -f <(paste access.log.IPs randomIPs.txt | awk '{ print "s/" $1 "/" $2 "/g" }') access.log

( , )

+2

bash lib :

# parse a template and return it
# 1st arg is template tags [array]
# 2nd arg is replacement values for template tags [array]
# 3rd arg is template file path
# usage: TT=$(parseTemplate TAGS[@] REPLACE[@] $MAIL_TEMPLATE); echo $TT;
function parseTemplate()
{
    local _TAG=("${!1}")
    local _REPLACE=("${!2}")
    local _TEMPLATE="${3}"
    local _PATTERN=""
    local i

    if [[ ${#_TAG[@]} > 0 ]]; then
        _PATTERN="-e s#\%\%${_TAG[0]}\%\%#${_REPLACE[0]}#g"
        for (( i = 1 ; i < ${#_TAG[@]} ; i++ ))
        do
            _PATTERN="${_PATTERN}; s#\%\%${_TAG[${i}]}\%\%#${_REPLACE[${i}]}#g"
        done

        local SED=`which sed`
        $SED "${_PATTERN}" < "${_TEMPLATE}"
    else
        local CAT=`which cat`
        $CAT "${_TEMPLATE}"
    fi
}

: %%TAG%% , ,

( ):

Hello %%NAME%%, your location is %%LOCATION%%


TAGS = ('NAME' 'LOCATION');
REPLACE = ('Nikos' 'GR')
TT=$(parseTemplate TAGS[@] REPLACE[@] $MAIL_TEMPLATE); 
echo $TT;

http://www.thegeekstuff.com/2010/06/bash-array-tutorial/

0

All Articles