sed replace literal TAB

≯℡__Kan透↙ 提交于 2019-12-06 02:53:53

问题


I want to replace TABs in stdout with semicolons, by running sed from the ZSH shell.

I understand one can normally (in other shells?) use:

somecommand | sed 's/\t/;/g'

However, this doesn't work for me in ZSH-shell under FreeBSD. The \t doesn't match the tabulators. Why is this? I've also tried multiple backslashes (up to 5).


This does work:

somecommand | sed 's/[TAB]/;/g'

, where [TAB] is an actual TAB-character, inserted by entering Ctrl-V followed by the TAB button on my keyboard.


回答1:


Use of zsh has nothing to do with it. The \t is a GNU extension to the regular expressions used in sed. On a BSD sed, you don't have the extensions, so have to use the literal tab.




回答2:


One option is to prepare your sed script ahead of time with printf.

scr="`printf 's/\t/;/g'`"
somecommand | sed "$scr"

But Michael++... There may be other sed variants that also support printf-style escapes, but it's certainly not "standard".




回答3:


If you know the output of the command is normal text (only tabs & printable text), you could use:

somecommand | sed -E 's/[[:cntrl:]]/;/g'

-E turns on "extended" regular expressions, which can contain character class names.



来源:https://stackoverflow.com/questions/8400602/sed-replace-literal-tab

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