【发布时间】:2021-01-16 22:41:41
【问题描述】:
这是一个 target.txt 文件的内容:
line1
line2
Environment=xLink=https://11111/route
line4
line5
我正在尝试编写一个 bash 脚本,它会找到包含“https”的行号,然后用 bash 脚本中获得的新字符串变量替换整行,这是没有替换行的 bash 脚本:
#!/bin/bash
x="12345"
route="/route"
x_route="${x}${route}"
x_init="Environment=xLink=https://"
new_line="${x_init}${x_route}"
echo "${new_line}"
to_replace_line_number=$(find target.txt -type f | xargs grep -n 'https' | cut -c1-2)
echo "${to_replace_line_number}"
targetfile=target.txt
echo "${targetfile}"
调用此脚本会按预期输出以下内容:
Environment=xLink=https://12345/route
3:
target.txt
现在,没有 bash 脚本,如果我调用:
sudo sed -i '3 c\Environment=xLink=https://12345/route' target.txt
target.txt 根据需要更改为:
line1
line2
Environment=xLink=https://12345/route
line4
line5
但目标是自动化,所以我尝试使用 sed 命令在 bash 脚本中完成这项工作。到目前为止,我尝试了两种方法,都没有奏效。
方法一: 我在 bash 脚本中添加了以下行:
sudo sed -i "${to_replace_line_number}s/.*/${new_line}/" ${targetfile}
当我运行脚本时,它没有工作,我得到了这个错误:
sed: -e expression #1, char 2: : doesn't want any addresses
方法二: 我在 bash 脚本中添加了以下命令:
sudo sed -i "${to_replace_line_number} c\${new_line}" ${targetfile}
当我运行脚本时,它没有工作,我得到了这个错误:
sed: -e expression #1, char 2: : doesn't want any addresses
我到底错过了什么?非常感谢任何帮助。
【问题讨论】:
-
假设
${to_replace_line_number}==3:,你的sed变成:sed -i "3: c\...;这似乎与关于char 2==:的错误消息相匹配;当sed能够找到并替换包含https的行而不需要任何行号时,为什么还要跳过查找行号的麻烦? -
哦,我试过了,但无法正常工作。我已经在努力让 sed 做一件特定的事情,即用字符串变量替换第 3 行。我显然还没有准备好或无法在 bash 脚本中调用单个 sed 命令来查找该行并替换它,您能否分享您的方法或代码行或其他内容?