找到值,但通过bash替换另一行中的另一行

时间:2016-09-14 09:05:09

标签: bash perl sed grep gawk

我必须将一些页面移动到另一台主机,但db IP已被拆分。 所以我必须找到一个用户名的值并替换IP上面的两行

我试过这个:

#!/bin/bash

OUTPUT="$(find /home/user/files/script/test-file -maxdepth 1 -iname  file_with_many_sqlconnections.php -exec grep -Hina -B 2 u1_3347 {} \; | grep 172)"

echo "${OUTPUT}"

LINE="$(echo "$OUTPUT" | cut -d"-" -f3 )"
echo "${LINE}"

FILE="$(echo "$OUTPUT" | cut -d"-" -f1,2)"

echo "${FILE}"

CONTENT="$(echo "$OUTPUT" | cut -d"-" -f4 | cut -d"." -f4 | cut -d "\"" -f1)"

echo "${CONTENT}"

gawk -v line="$LINE" -v content="$CONTENT" -v file="$FILE" -i inplace "NR=="line"{gsub("content", 177)}1" "$FILE"

我尝试了几个变量组合,quotevariants,反之亦然。 我还尝试了sedperl,但是我输出了垃圾,EOF之后的换行问题,或者gawk忽略了换行符并尝试将所有内容整合到一个命令。

我只使用echo段来查看结果的结果是否正常,而且正如我在shell中看到的那样,它会显示"很好。

问题

  $db = mysql_connect("172.1.1.178",
     "u2_3456","pass6");


    $db = mysql_connect("172.1.1.178",
     "u1_3347","pass7");


    $db = mysql_connect("172.1.1.178",
     "u1_3347","pass7");


    $db = mysql_connect("172.1.1.178",
     "u2_3456","pass6");


    $db = mysql_connect("172.1.1.178",
     "u1_3347","pass7");

应该是:

 $db = mysql_connect("172.1.1.178",
  "u2_3456","pass6");


 $db = mysql_connect("172.1.1.180",
  "u1_3347","pass7");


 $db = mysql_connect("172.1.1.180",
  "u1_3347","pass7");


 $db = mysql_connect("172.1.1.178",
  "u2_3456","pass6");


 $db = mysql_connect("172.1.1.180",
  "u1_3347","pass7");


 $db = mysql_connect("172.1.1.180",
  "u1_3347","pass7");

问题

  $db = mysql_connect("172.1.1.178",
     "u2_3456","pass6");


    $db = mysql_connect("172.1.1.178",
     "u1_3347","pass7");

1 个答案:

答案 0 :(得分:0)

处理您的样本输入(即跳过文件读取等):

perl -0777 -pe "s/(\$db = mysql_connect\()\"\d+\.\d+\.\d+\.\d+(\",\s*\n)\s*(\"u1_3347\")/ \1\"172.1.1.180\2  \3/g"

详细说明:

  • 使用-0777完全吃掉输入,
    允许模式匹配换行符
  • -pe默认循环输入和打印结果
  • 查找几乎任何IP地址,
    嵌入所需输入线的特征其他部分
  • 专门查找需要更改IP的用户
  • 从空格,捕获组和新IP组装新输出行
  • 到处g

输出(根据需要,除了空白修补,只有样本输入的五个条目):

  $db = mysql_connect("172.1.1.178",
     "u2_3456","pass6");


     $db = mysql_connect("172.1.1.180",
  "u1_3347","pass7");


     $db = mysql_connect("172.1.1.180",
  "u1_3347","pass7");


    $db = mysql_connect("172.1.1.178",
     "u2_3456","pass6");


     $db = mysql_connect("172.1.1.180",
  "u1_3347","pass7");