简体   繁体   English

如何只保留一个空格的字符串并使用sed替换所有其他空格?

[英]How can I keep the string of one space only and replace all the other spaces using sed?

  • I have a data file (1.data) which contains the following: 我有一个数据文件(1.data),其中包含以下内容:

      USSR 8649 BS275 Asia Cananda 3852 BS25 North America 

    What I want is to keep the string of only one space and replace all the other spaces with : 我想要的是仅保留一个空格的字符串,并用:替换所有其他空格:

My sed code: 我的sed代码:

sed 's/ *   */:/g' 1.data

:USSR:8649:BS275:Asia
:Cananda:3852:BS25:North America

That works perfect. 完美的作品。

Since I know A+ matches A, AA, AAA, AAAA and so on, I tried another regular expression. 由于我知道A +匹配A,AA,AAA,AAAA等,因此我尝试了另一个正则表达式。

sed 's/ *  +/:/g' 1.data



          USSR                  8649                 BS275                  Asia
       Cananda                  3852                  BS25         North America

However, it does not work. 但是,它不起作用。 Nothing changes. 没有什么变化。

What mistake did I make? 我犯了什么错误?

添加选项-E (从正则表达式切换为扩展正则表达式)或将+替换为\\+

sed would treat "+" as a normal character if no -r option is added. 如果未添加-r选项,则sed会将“ +”视为普通字符。 And "+" meta-character would match to one or more after -r: extended regular expressions is added. -r: extended regular expressions之后,“ +”元字符将匹配一个或多个-r: extended regular expressions添加了-r: extended regular expressions So your command can be modified as, 因此您的命令可以修改为

sed -r 's/[[:space:]]+/:/g' 1.data

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用sed,我如何用Y替换X的所有出现,但只能在看到Z之后? - Using sed, how can I replace all occurences of X with Y, but only after seeing Z? 如何在Linux中使用tr或sed命令将一个字符替换为另外两个字符? - How can I replace a space a character for two other characters in linux with tr or sed command? 用一个空格替换所有空格,用一个新行替换所有新行 - Replace all spaces with only one space and all the new lines with only one new line 如何删除字符串列表中列出的所有字符串,但只能删除空格后面的字符串 - How can i remove all string that listed on a list of strings, but only the one that followed by space SQLServer,如何只用一个替换所有空格序列 - SqlServer, how to replace all spaces sequences with only one 查找/保存:如何递归搜索/替换文件中的字符串,但仅查找与特定正则表达式匹配的行 - Find/sed: How can I recursively search/replace a string in files but only for lines that match a particular regexp sed查找并替换带空格的字符串 - sed find and replace a string with spaces 如何替换sed中匹配字符串中的所有字符 - How can I replace all occurrences of a character within matched string in sed 如何使用sed将字符串'AllowOverride None'的第二次出现替换为'AllowOverride All' - How do I replace the second occurrence of string 'AllowOverride None' with 'AllowOverride All' using sed 如何使用sed用逗号替换空格? - How to replace space with comma using sed?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM