在sed中插入标签的正确方法是什么?

问题描述 投票:16回答:7

在sed中插入标签的正确方法是什么?我正在使用sed将标题行插入流中。之后我可能会使用正则表达式替换某个字符,但是有没有更好的方法呢?

例如,假设我有:

some_command | sed '1itextTABtext'

我希望第一行看起来像这样(文本由制表符分隔):

text    text

我尝试用“\ t”,“\ x09”,“”(标签本身)替换上面命令中的TAB。我用双引号和没有双引号尝试了它,我不能让sed在文本之间插入制表符。

我试图在SLES 9中这样做。

linux sed
7个回答
11
投票

您可以正确使用sed i命令:

some_command | sed '1i\
text    text2'

在哪里,我希望很明显,'text'和'text 2'之间有一个标签。在Mac OS X(10.7.2)上,因此可能在其他基于BSD的平台上,我能够使用:

some_command | sed '1i\
text\ttext2'

sed\t翻译成一个标签。

如果sed不解释\t并在命令行插入制表符是一个问题,请使用编辑器创建一个shell脚本并运行该脚本。


12
投票

假设bash(也许其他shell也会起作用):

some_command | sed $'1itext\ttext'

Bash将在\t中处理逃逸,例如$' ',然后将其作为arg传递给sed。


3
投票

Sed可以做到这一点,但它很尴尬:

% printf "1\t2\n3\t4\n" | sed '1i\\
foo bar\\
'
foo bar
1   2
3   4
$

(双反斜杠是因为我使用tcsh作为我的shell;如果你使用bash,使用单反斜杠)

foo和bar之间的空格是一个选项卡,我通过在CtrlV前面加上它来键入。您还需要使用CtrlV在单引号中添加换行符。

使用awk执行此操作可能更简单/更清楚:

$ printf "1\t2\n3\t4\n" | awk 'BEGIN{printf("foo\tbar\n");} {print;}'

3
投票

正如大多数答案所说,可能字面上的tab字符是最好的。

info sed说“\ t不便携。” :

... '\CHAR' Matches CHAR, where CHAR is one of '$', '*', '.', '[', '\', or '^'. Note that the only C-like backslash sequences that you can portably assume to be interpreted are '\n' and '\'; in particular '\t' is not portable, and matches a 't' under most implementations of 'sed', rather than a tab character. ...


1
投票

我找到了一种通过替换来插入标签的替代方法。

some_command | sed '1s/^/text\ttext\n/'

我仍然不知道使用insert方法的方法。


1
投票

为了说明BRE syntax for sed确实提到\t不便携的事实,Git 2.13(2017年第二季度)摆脱了它。

请参阅commit fba275d撰写的Junio C Hamano (gitster)(2017年4月1日)。 (Junio C Hamano -- gitster --合并于commit 3c833ca,2017年4月17日)

contrib/git-resurrect.sh:不要在\t脚本中为HT写sed

就像我们在0d1d6e5中所做的那样(“t/t7003:用\t表达式中的文字标签替换sed”,2010-08-12,Git 1.7.2.2),避免在\t脚本中为HT编写“sed”,这是不可移植的。

-   sed -ne 's~^\([^ ]*\) .*\tcheckout: moving from '"$1"' .*~\1~p'     
+   sed -ne 's~^\([^ ]*\) .*     checkout: moving from '"$1"' .*~\1~p'
                            ^^^^
                             |
                        (literal tab)

1
投票

转义制表符:

sed -i '/<setup>/ a \\tmy newly added line' <file_name>

注意:上面我们有两个反斜杠(\),第一个用于转义(),下一个是实际的tab char(\ t)

© www.soinside.com 2019 - 2024. All rights reserved.