bash 用管子解开

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16332305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:19:26  来源:igfitidea点击:

Unescape with pipe

bashsedpipe

提问by Steven Penny

Given this file

鉴于此文件

$ cat foo.txt
\"That's funny, haha\"

I can unescape the double quotes with read

我可以用 read

$ read bar < foo.txt

$ echo $bar
"That's funny, haha"

However can this be done with a pipe? Something like

但是,这可以用管道完成吗?就像是

cat foo.txt | unescape

回答by Steven Penny

This seems to do it

这似乎做到了

sed -r 's/\(.)//g'

回答by cdarke

Yes or no, depending on what you mean by your question. The pipe cannot remove the backslash, but, as you saw, readcan:

是或否,取决于您的问题的意思。管道不能删除反斜杠,但是,如您所见,read可以:

cat foo.txt | read bar

This is, though, a useless use of catAND it won't do what you need anyway.

但是,这是对catAND的无用使用,无论如何它不会做你需要的。

In Bash, this has the added "feature" that each side of the pipe runs in it's own process. This means that the variable (bar) will not be available in the calling process. So, the backslashes will be removed but it won't do you a bit of good.

在 Bash 中,这具有附加的“功能”,即管道的每一侧都在其自己的进程中运行。这意味着变量 ( bar) 在调用过程中将不可用。因此,反斜杠将被删除,但这对您没有任何好处。

Yes, you couldcontrive to capture it:

是的,您可以设法捕获它:

bar=$(cat foo.txt | { read bat;echo $bat;})

But that's not just horrible to look at, it is inefficient as well.

但这不仅看起来很糟糕,而且效率很低。

Stick to redirection.

坚持重定向。

回答by Ian Puleston

This is an old question now, but I'll add this answer so that it's here for the record since I had the same question and couldn't find a solution anywhere. I came up with this solution which works for any string escape sequences:

这是一个老问题,但我会添加这个答案,以便记录在这里,因为我有同样的问题并且在任何地方都找不到解决方案。我想出了这个适用于任何字符串转义序列的解决方案:

echo "" | gawk "{ print \"\`cat foo.txt\`\" }"

echo "" | gawk "{ print \"$(cat foo.txt)\" }"

echo "" | gawk "{ print \"$(< foo.txt)\" }"

They're all variants of the same operation, and note the use of backquotes in the first one. They are utilizing the unescaping done by gawk's print command, and are limited to a one-line input file (although I'm sure that a more complex variant could be worked out for multi-line input).

它们都是相同操作的变体,请注意在第一个操作中使用反引号。他们正在利用由 gawk 的打印命令完成的转义,并且仅限于一行输入文件(尽管我确信可以为多行输入计算出更复杂的变体)。

Note that cat foo.txt | gawk '{ printf $0 }', which I thought might be a solution, doesn't work - it seems that gawk doesn't unescape its input, even when that is used as the printf format string which it would otherwise unescape.

请注意cat foo.txt | gawk '{ printf $0 }',我认为这可能是一个解决方案,但它不起作用 - 似乎 gawk 不会对其输入进行转义,即使将其用作 printf 格式字符串,否则它会转义。