GNU sed - find or replacing spaces or new lines. W

2019-07-21 16:18发布

C:\crp\cnp>sed -V

GNU sed version 3.02

Copyright (C) 1998 Free Software Foundation, Inc.......


C:\crp\cnp>type f.f

a a a

a a a

Trying to replace 'a' with spaces.

C:\crp\cnp>type f.f | sed -e s/a/\d032/g

d032 d032 d032

d032 d032 d032

why isn't it working?

I don't mind whether i'm finding or replacing spaces or new lines.. I just want to be able to specify them. It doesn't seem to be working and I don't know why.

(Replacing spaces or a space, with f, doesn't work)

C:\crp\cnp>echo a a | sed s/\d32/f/
a a

Note- it seems it might work in 4.2 , But i'm interested in 3.02 'cos that's the version bundled with unxutils http://unxutils.sourceforge.net/

Update to question- thanks for paxdiablo's tip.. about gnu32win, I am now using that instead of unxutils. It is more up to date. I can now specify spaces. And tip of ghostdog, and paxdiablo, I see about the double quotes. I am fine specifying spaces with \d(since using 4.2) or with a space. But, I still can't remove new lines

C:\crp>type f.f | sed -e "s/\r\n/f/g"

a aa

b bb

c cc

C:\crp>type f.f | sed -e "s/\d013\d010/f/g"

a aa

b bb

c cc

C:\crp>type f.f | sed -e "s/\x0D\x0A/f/g"

a aa

b bb

c cc

3条回答
Lonely孤独者°
2楼-- · 2019-07-21 16:48

Why aren't you just using a space character itself rather than some funny encoding? As in:

sed -e 's/a/ /g'

For what it's worth, the command you gave also fails to work in 4.2.1 but, if you add in the quotes, it does work. So I suggest you change it to:

sed -e 's/a/\d032/g'

Apologies, I've just noticed you're running Windows so you've probably got CygWin or GnuWin32 (or equivalent).

Quotes work differently under Windows so you should try two things. The first is to use " instead of ' quotes:

sed -e "s/a/ /g"

Otherwise, the escape character in Windows is ^ so something like this should be able to escape the space:

sed -e s/a/^ /g

As an aside, I'd be looking to switch to GnuWin32, if possible, which has more recent versions of sed (for example). It doesn't look like UnxUtils has had an update since 2003 based on that web page you link to. You can get individual packages from here. You're looking for coreutils which contains the bulk of the UNIX text processing toolkit.

But, if you're stuck with UnxUtils, I'd just use the actual space rather than a decimal code, and then I'd use tr to get rid of new lines:

tr -d "\n"

assuming of course that the tr in textutils can handle that syntax :-)

查看更多
唯我独甜
3楼-- · 2019-07-21 16:50

I stuck with the same problem on Win XP and double quotes didn't work when trying to print new line "\n". The solution was to use the new UnxUpdates.zip from http://unxutils.sourceforge.net/ It works correct with "\n".

Sed version states: GNU sed version 4.0.7

查看更多
4楼-- · 2019-07-21 16:56

On windows, use double quotes

sed "s/a/\d032/g" file

or just

sed "s/a/ /g" file
查看更多
登录 后发表回答