使用sed的条件语句

时间:2014-03-27 16:47:05

标签: bash shell sed

我需要根据以下规则处理大量文件:

如果文件以#开头,则在第二行的开头插入#。 否则,在文件的开头插入#

要在第1行的开头插入#,我会sed '1s/^/#/' myfile

要在第二行的开头插入#,我会sed '2s/^/#/' myfile

但是,我在这里错过了条件逻辑。如何根据我上面仅使用sed?

编写的条件语句对这些操作进行排序

5 个答案:

答案 0 :(得分:1)

awk具有正确的逻辑,但不确定如何使用多个文件

awk 'FNR==1 {if (/^#/) {print;getline};print "#"$0;next} 1' file

答案 1 :(得分:1)

sed不太适合这类事情,但这应该有效:

sed  '1{ /^#/{N;s/\n/\
#/; }; /^#/!s/^/#/; }; '

答案 2 :(得分:1)

这可能适合你(GNU sed):

sed '1{N;/^#/s/\n/&#/;t;s/^/#/}' file

读取前两行,如果第一行以#开头,则在第二行插入#,或在第一行插入' #`(如果没有)。

答案 3 :(得分:0)

这是一种非常易读的方式:

awk 'BEGIN{OFS=""}
     NR==1 {if(/^#/){PRE="#"} else {sub(/^/,"#",$0)} print;next}
     {print PRE,$0;PRE=""}' file

BEGIN {}设置字段分隔符。

第二行适用于文件的第1行,并为下一行设置PREFIX为#,或者在当前行的开头替换#。然后打印出来,避免下一个陈述。

第三行打印文件的所有后续行,第二行打印前缀为#(如果需要)。

答案 4 :(得分:0)

如果仅用于教学目的,这里是实际使用条件分支的sed行:

sed '1{s/^\([^#]\)/#\1/;t;n;s/^/#/}'

大致是:

if on the first line:
    if the line starts with anything other than '#'
        insert '#' at the beginning
    else
        print the line as is
        read the next line
        insert '#' at the beginning

更短,但无条件分支:

sed '1{/^#/{n;s/^/#/;b};s/^/#/}'

大致是:

if on the first line:
    if the line starts with '#'
        print the line
        read the next line
        insert '#' at the beginning
        skip to the end
    (implied else)
        insert '#' at the beginning
相关问题