sed无法从bash脚本中运行

权利

我已经阅读了有关此主题的所有类似问题,但是没有找到与我所遇到的问题相匹配的问题。如果这个问题已经得到回答,我深表歉意。

在我编写的bash脚本中,有一个非常简单的sed命令,该命令似乎不起作用。没有错误,并且从命令行运行时,该命令可以完美运行。

在set -x的输出中,我可以看到sed命令执行得很好。

GNU bash版本4.3.11(1)-发行版(x86_64-pc-linux-gnu)

Bash脚本:(调低以更容易理解)

#!/bin/bash -x

# This script has the exact same sed command as used on cli

contact='"[email protected]"'

sed -i "/$contact/d" /home/tim/Desktop/file.txt

exit

外壳输出:

tim@ubuntu:~/Desktop$ cat file.txt
t,b,[email protected]
tim@ubuntu:~/Desktop$ ./test.sh 
+ contact='"[email protected]"'
+ sed -i '/"[email protected]"/d' /home/tim/Desktop/file.txt
+ exit
tim@ubuntu:~/Desktop$ cat file.txt
t,b,[email protected]
tim@ubuntu:~/Desktop$ sed -i "/"[email protected]"/d" /home/tim/Desktop/file.txt
tim@ubuntu:~/Desktop$ cat file.txt
tim@ubuntu:~/Desktop$

我认为我遗漏了一些非常明显的东西,但是我已经盯着它看了,希望答案从屏幕上跳下来并打我一巴掌。请帮忙 :-)

提姆

崩溃

$contact脚本变量中的邮件地址周围有双引号,但命令行调用中没有这些双引号

# case 1 - works
# only the sed pattern delimiters are enclosed in quotes and these quotes will be stripped by the shell. 
sed -i "/"[email protected]"/d" ./file.txt; cat file.txt

# case 2 - fails
# escaping with \ turns dquotes #2,3 from shell-level delimiters to char literals w/o special  semantics.
sed -i "/\"[email protected]\"/d" ./file.txt; cat file.txt

# case 3 - fails
# Single quotes enclose the complete sed pattern spec which comprises double quotes enclosing the mail address
sed -i '/"[email protected]"/d' ./file.txt; cat file.txt

# case 4 - works
sed -i "/[email protected]/d" ./file.txt; cat file.txt

# case 5 - works
sed -i '/[email protected]/d' ./file.txt; cat file.txt

这将解释脚本与cli调用的不同行为。

OP指出,他需要在真实脚本中使用双引号。可能是这样,但是,如果文件中不存在这些双引号,将没有匹配项。

一种解决方案是使用sed预处理文件(如有必要,对副本进行处理):

sed -i 's/,/","/g; s/^/"/; s/$/"/' ./file.txt

该命令假定每行的项目以逗号分隔,没有包含双引号的项目。它将每个项目都用双引号引起来,因此它们将与原始脚本$contact变量中的搜索模式匹配

替代方案(改编自该SO答案[我还不是作者])

另一种选择是通过从中派生第二个变量来更改脚本的相关部分$contact

contact='"[email protected]"'
c2=$(echo $contact | tr -d '"')

sed -i "/$c2/d"  /home/tim/Desktop/file.txt

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

无法在 Bash 脚本上运行 sed 命令

来自分类Dev

无法在bash脚本中运行adb命令

来自分类Dev

Bash 脚本无法在 Shell 中运行

来自分类Dev

无法从bash脚本运行bash脚本

来自分类Dev

sed命令可在终端中运行,但不能通过bash_aliases或bash脚本运行

来自分类Dev

sed命令可在终端中运行,但不能通过bash_aliases或bash脚本运行

来自分类Dev

Bash脚本无法运行

来自分类Dev

Incron无法运行bash脚本

来自分类Dev

SFTP的期望脚本无法在bash中运行

来自分类Dev

无法在 PHP Exec 中以 root 身份运行 BASH 脚本

来自分类Dev

Bash脚本查找/ SED无法正常工作

来自分类Dev

Sed Bash 脚本只运行 sed 的第一行

来自分类Dev

在bash脚本中运行apktool

来自分类Dev

在新贵的.conf脚本中运行bash脚本

来自分类Dev

在Expect脚本中运行bash脚本

来自分类Dev

在bash脚本中运行powershell脚本

来自分类Dev

在Expect脚本中运行bash脚本

来自分类Dev

Bamboo Plan脚本无法在bash脚本中运行正则表达式

来自分类Dev

在Perl脚本中运行sed命令

来自分类Dev

Bash脚本无法从crontab正常运行

来自分类Dev

无法获取Crontab来运行Bash脚本

来自分类Dev

运行bash脚本后无法启动

来自分类Dev

运行bash脚本时无法自行统计

来自分类Dev

OSX bash脚本无法从cron运行

来自分类Dev

sed无法使用bash脚本注释文件中的一行

来自分类Dev

sed 无法处理 bash 脚本中的变量;请求文件。简单的例子

来自分类Dev

sed抱怨bash脚本中的数字

来自分类Dev

在bash脚本中执行sed命令

来自分类Dev

sed抱怨bash脚本中的数字