1

How can I do this?

[root@ipaserver ~]# ls | sed 's/.*/"&"/'
"anaconda-ks.cfg"
"ca-agent.p12"

Like this?

[root@ipaserver ~]# !QUOTED
QUOTED="sed 's/.*/\"&\"/'"
[root@ipaserver ~]# echo $QUOTED
sed 's/.*/"&"/'
[root@ipaserver ~]# ls| $QUOTED
sed: -e expression #1, char 1: unknown command: `''

I've tried all kinds of variations and nested echo command/process substitutions and eval. Is this possible to do for scripting purposes?

4

4 回答 4

4

One way:

QUOTED='sed s/.*/"&"/'
ls | $QUOTED
于 2013-05-28T03:29:48.067 回答
2

What you have there works fine for me with the addition of an eval:

$ QUOTED="sed 's/.*/\"&\"/'"
$ echo $QUOTED
sed 's/.*/"&"/'
$ ls | eval $QUOTED
"file1"
"file2"
"file3"
"file4"
于 2013-05-28T03:29:10.333 回答
1

you want a shell alias here

alias QUOTED='sed "s/.*/\"&\"/"'

As you can see, the quoting gets a little tricky. Using a function is clearer

unalias QUOTED
QUOTED() { sed 's/.*/"&"/'; }

In both cases:

$ printf "%s\n" foo bar baz | QUOTED
"foo"
"bar"
"baz"
于 2013-05-28T11:07:38.823 回答
0

Usually, the best way to handle this sort of thing is storing the command as an array:

sedcmd=(sed 's/.*/"&"/')
ls | "${sedcmd[@]}"

See BashFAQ #50:I'm trying to put a command in a variable, but the complex cases always fail! for more options and discussion.

于 2013-05-28T04:43:23.887 回答