最简单的方法来代替空格与(下划线)_在bash [英] The easiest way to replace white spaces with (underscores) _ in bash

查看:913
本文介绍了最简单的方法来代替空格与(下划线)_在bash的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我不得不写在XenServer的解析虚拟机的一个小脚本,并为虚拟机的名称大多是在例如Windows XP或Windows Server 2008的白色空间,我不得不削减这些空格,并用下划线代替他们_ 。我发现了一个简单的解决办法做到这一点使用sed的,这是伟大的工具,当它涉及到字符串操作。

 回声这仅仅是一个测试| SED -e'S / / _ / G'

返回

  This_is_just_a_test


解决方案

您可以只使用外壳做到这一点,没有必要 TR SED

  $海峡=这仅仅是一个测试
$回声$ {// STR / _}
This_is_just_a_test

recently I had to write a little script that parsed VMs in XenServer and as the names of the VMs are mostly with white spaces in e.g Windows XP or Windows Server 2008, I had to trim those white spaces and replace them with underscores _ . I found a simple solution to do this using sed which is great tool when it comes to string manipulation.

echo "This is just a test" | sed -e 's/ /_/g'

returns

This_is_just_a_test

解决方案

You can do it using only the shell, no need for tr or sed

$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test

这篇关于最简单的方法来代替空格与(下划线)_在bash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆