我的脚本中有一个 sed 命令,它在作为变量传递给命令的文本的特定部分之间打印数据:
sed -n "$PART1|,|$PART2|p" file.txt
在我尝试包含双重qoute的文本的一部分之前,一切都很好。例如,PART1 = of the Rings"
和PART2 = Sauron
。
我尝试将语法更改为
sed -n '$PART1|,|$PART2|p' file.txt
然而,它根本不喜欢它。
有没有办法自动转义传递给带有变量的 sed 的双引号?此外,无法更改源文件中的双引号。
感谢您提出任何建议。
答案 0 :(得分:1)
让我们从这个测试文件开始:
$ cat file
something
of the Rings"
keep this text
Dark Lord Sauron
something else
让我们定义你的变量:
$ part1='of the Rings"'
$ part2=Sauron
现在,让我们运行sed:
$ sed -n "/$part1/,/$part2/p" file
of the Rings"
keep this text
Dark Lord Sauron
如果您真的更喜欢管道符号来代替/
:
$ sed -n "\|$part1|,\|$part2|p" file
of the Rings"
keep this text
Dark Lord Sauron
执行此操作时的一个问题是part1
和part2
成为sed命令的一部分,如果恶意构造,可能会损坏您的文件。对于这种情况,使用awk更安全。
$ awk -v p="$part1" -v q="$part2" '$0~p,$0~q' file
of the Rings"
keep this text
Dark Lord Sauron
答案 1 :(得分:0)
永远不要将脚本括在双引号中,总是单引号,以避免意外的shell交互,并且不会按惯例使用非导出变量的所有大写名称,并避免与内置变量发生冲突。借用@ John1024的样本输入文件:
$ cat file
something
of the Rings"
keep this text
Dark Lord Sauron
something else
$ sed -n '/'"$part1"'/,/'"$part2"'/p' file
of the Rings"
keep this text
Dark Lord Sauron
但更强大,更可扩展,您应该使用这样的awk脚本:
$ awk -v part1="$part1" -v part2="$part2" '$0~part1{f=1} f; $0~part2{f=0}' file
of the Rings"
keep this text
Dark Lord Sauron
并且不使用范围表达式。例如,不打印整个范围的行是一个简单的调整与标志方法:
$ awk -v part1="$part1" -v part2="$part2" 'f; $0~part1{f=1} $0~part2{f=0}' file
keep this text
Dark Lord Sauron
$ awk -v part1="$part1" -v part2="$part2" '$0~part1{f=1} $0~part2{f=0} f' file
of the Rings"
keep this text