problem with sed on command line

802 views
Skip to first unread message

Paul

unread,
Mar 14, 2011, 12:26:35 PM3/14/11
to Linux Users Group
Hello,

I am struggling to find a solution to the following apparently simple
problem, so any help would be much appreciated.

Here is a simple example of what I'm trying to do.

From the console of a linux machine running Fedora-12, if I do

echo "AB" > file
FILE=file

sed "s/AB/12/" $FILE

I get, as expected,

12

I can also do

COMMAND="sed s/AB/12/ $FILE"
$COMMAND

and again I get

12

So far so good. If, however, I now introduce a space with

echo "A B" > file

I'd like to find the setting for COMMAND which is equivalent to

sed "s/A B/1 2/" $FILE
1 2

I've tried a number of obvious variations, but I can't get any to
work, for example,

COMMAND="sed s/A B/1 2/ $FILE"
$COMMAND
sed: -e expression #1, char 3: unterminated `s' command

COMMAND="sed \"s/A B/1 2/\" $FILE"
$COMMAND
sed: -e expression #1, char 1: unknown command: `"'

COMMAND='sed "s/A B/1 2/" $FILE'
$COMMAND
sed: -e expression #1, char 1: unknown command: `"'

COMMAND="sed 's/A B/1 2/' $FILE"
$COMMAND
sed: -e expression #1, char 1: unknown command: `''


Thanks,

Paul

Chris Miller

unread,
Mar 14, 2011, 12:50:32 PM3/14/11
to linuxus...@googlegroups.com, Paul
cmiller@elder-miller-ubuntu:~/tmp$ echo "A B" > foboar.
cmiller@elder-miller-ubuntu:~/tmp$ sed "s/A\ B/1\ 2/" foboar.
1 2

You need to escape the whitespace with a backslash (or backwhack in
Microsoft-nese, for those interested).

> --
> You received this message because you are subscribed to the Linux Users Group.
> To post a message, send email to linuxus...@googlegroups.com
> To unsubscribe, send email to linuxusersgro...@googlegroups.com
> For more options, visit our group at http://groups.google.com/group/linuxusersgroup

--
Registered Linux Addict #431495
For Faith and Family! | John 3:16!
fsdev.net
0x5f3759df.org

Daniel Eggleston

unread,
Mar 14, 2011, 1:41:20 PM3/14/11
to linuxus...@googlegroups.com
You don't need to escape the spaces (try it - do exactly what cmiller did, without the backwhacks, and it will work fine).

However, Paul's storing the data in a variable, and the double quotes get passed to the sed command verbatim, and sed can't handle the quotes. 

One easy solution is to use a couple of variables, instead of one:

[ degglest@tavanasa : /net_home/degglest ]
$ COMMAND='sed'; ARG='s/A B/1 2/'
[ degglest@tavanasa : /net_home/degglest ]
$ echo "A B" | $COMMAND "$ARG"
1 2
           Daniel

Paul Stansell

unread,
Mar 14, 2011, 6:14:32 PM3/14/11
to linuxus...@googlegroups.com
Dear Daniel,

Thanks very much for your example, it's exactly what I needed!

Paul

Reply all
Reply to author
Forward
0 new messages