SED找到替代使用bash阵列失败 [英] sed find replace using bash arrays fails

查看:145
本文介绍了SED找到替代使用bash阵列失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个文件,两个文件在每个文件2259的IP地址。一个文件与137772.脚本使用使用bash阵列sed和一个for循环来在不同的IP的access.log的更换IP地址。几个小时运行该脚本后失败,此错误:

的sed:-e前pression#1,烧焦0:无previous定期EX pression

uniq的IP地址的数量也由六个IP的短

下面是脚本:

 #!/斌/庆典
_ORGIFS = $ IFS
IFS = $'\\ n'
_alIPs =($(小于access.log.IPs)
_fIPs =($(小于randomIPs.txt)
为((_i = 1; _i&下; = 2259; _i ++))

  SED -iS / $ {_ ALIPS [$ _ I]} / $ {_ FIPS [$ _ I]} / G的access.log
DONE
IFS = $ _ ORGIFS


解决方案

数组索引在bash从0开始。当你说

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

您忽略第一项,并走一过去的结束,在这一点

  SED -iS / $ {_ ALIPS [$ _ I]} / $ {_ FIPS [$ _ I]} / G的access.log

扩展到

  SED -iS //东西/ G的access.log

// 取值命令尝试重用previously经常使用前pression,它不存在,所以你得到的错误。

的解决方案是使用

 为((_ I = 0;&_I LT; 2259; _i ++))

...虽然,说真的,我会花一些时间思考如何做那些替代散装。

附录:

  SED -i -f≤(粘贴access.log.IPs randomIPs.txt | awk的'{打印S /$ 1/$ 2/ G}) access.log的

(假设我正确地读出你的意图)

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

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

The number of uniq IP addresses is also short by six IPs.

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

解决方案

Array indices in bash start at 0. When you say

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

you ignore the first entry and go one past the end, at which point

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

expands to

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

The // in the s command attempts to reuse the previously used regular expression, which doesn't exist, and so you get the error.

The solution is to use

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

...although, seriously, I'd spend some time thinking about ways to do those replacements in bulk.

Addendum: Such as

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

(assuming I read your intentions correctly)

这篇关于SED找到替代使用bash阵列失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆