简体   繁体   中英

How to change some symbols (e.g. “space”) to other symbol in Bash/shell

I have some output from

ps -ef | grep apache

I need to change all spaces in that output to '@' symbol Is it possible to use some bash script for this? Thanks

使用tr

ps -ef | grep apache | tr ' ' @

use tr :

$ echo 'foo bar baz' | tr ' ' '@'
foo@bar@baz

( documentation )

Basic sed command:

ps -ef | grep apache | sed 's/ /@/g'

sed 's/text/new text/g' looks for "text" and replaces it with "new text".

In case you want to replace more characters, for example replace all spaces and _ with @ : (thanks Adrian Frühwirth ):

ps -ef | grep apache | sed 's/[_ ]/@/g'

如果使用awk则可以跳过多余的grep

ps -ef | awk '/apache/{gsub(/ /,"@");print}'

If you want multiple space characters to be replaced with only one @ symbol, you can use -s flag with tr :

ps -ef | grep apache | tr -s ' ' '@'

or this sed solution:

ps -ef | grep apache | sed -r 's/ +/@/g'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM