How to use GNU sed on Mac OS X

匿名 (未验证) 提交于 2019-12-03 03:00:02

问题:

Under Mac OS 10.10.3, I installed gnu-sed by typing:

brew install gnu-sed --default-names 

When I type it again, I get the message:

gnu-sed-4.2.2 already installed

However, even after rebooting the system and restarting Terminal, I still cannot use the GNU version of sed. For example:

returns: bad flag in substitution command 'i'

What should I do to get the GNU version working? Here are the paths in my $PATH variable.

/Users/WN/-myUnix /opt/local/bin /opt/local/sbin /usr/bin /bin /usr/sbin /sbin /usr/local/bin /Applications/calibre.app/Contents/MacOS /opt/ImageMagick/bin /usr/texbin  

I'm sorry if my question seems obvious, but I am learning shell scripting on my own and don't quite understand yet how UNIX programs are installed. Any help to use GNU compliant commands (in this case sed, but soon I'll need others as well) on my Mac without causing damage or unnecessary clutter would be greatly appreciated.

回答1:

You already have the gnu-sed installed without the --with-default-names option.

  • With --with-default-names option it installs sed to /usr/local/bin/
  • Without that option it installs gsed

So in your case what you gotta do is:

$ brew uninstall gnu-sed $ brew install gnu-sed --with-default-names 

Update path if needed...

$ echo $PATH | grep -q '/usr/local/bin'; [ $? -ne 0 ] && export PATH=/usr/local/bin:$PATH $ echo a | sed 's_A_X_i' 

or use gsed as others suggested.



回答2:

When you install sed the gnu version, for mac os x using:

brew install gnu-sed 

The program that you use is gsed

so for example:



回答3:

The sed that ships with OS X is in /usr/bin.

The sed that homebrew installs is in /usr/local/bin.

If you prefer to use the homebrew one, you have two options:

Option 1

Every time you want to use homebrew sed, type

/usr/local/bin/sed 

or, preferably

Option 2

Move /usr/local/bin/ ahead (i.e. before) /usr/bin in your PATH in your login profile, like this

 export PATH=/usr/local/bin:


回答4:

If you install brew install coreutils, you'll get sed and a bunch of other GNU versions of things, like tar, date, etc. These are all installed in /usr/local/bin and given the prefix 'g'. So after installing, if you want the GNU version of sed, you'd type gsed instead. Works great.



回答5:

If you need to use gnu-sed command with their normal names, you can add a "gnubin" directory to your PATH from your bashrc. Just use the following command in your bash or terminal.

export PATH="/usr/local/opt/gnu-sed/libexec/gnubin:$PATH" 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!