我该怎么做?
[root@ipaserver ~]# ls | sed 's/.*/"&"/'
"anaconda-ks.cfg"
"ca-agent.p12"
喜欢这个吗?
[root@ipaserver ~]# !QUOTED
QUOTED="sed 's/.*/\"&\"/'"
[root@ipaserver ~]# echo $QUOTED
sed 's/.*/"&"/'
[root@ipaserver ~]# ls| $QUOTED
sed: -e expression #1, char 1: unknown command: `''
我尝试了各种变体和嵌套的echo命令/进程替换和eval。这可以用于编写脚本吗?
答案 0 :(得分:4)
一种方式:
QUOTED='sed s/.*/"&"/'
ls | $QUOTED
答案 1 :(得分:2)
通过添加eval
:
$ QUOTED="sed 's/.*/\"&\"/'"
$ echo $QUOTED
sed 's/.*/"&"/'
$ ls | eval $QUOTED
"file1"
"file2"
"file3"
"file4"
答案 2 :(得分:1)
你想要一个shell别名
alias QUOTED='sed "s/.*/\"&\"/"'
正如你所看到的,引用有点棘手。使用函数更清晰
unalias QUOTED
QUOTED() { sed 's/.*/"&"/'; }
在这两种情况下:
$ printf "%s\n" foo bar baz | QUOTED
"foo"
"bar"
"baz"
答案 3 :(得分:0)
通常,处理此类事情的最佳方法是将命令存储为数组:
sedcmd=(sed 's/.*/"&"/')
ls | "${sedcmd[@]}"
有关更多选项和讨论,请参阅BashFAQ #50:I'm trying to put a command in a variable, but the complex cases always fail!。