sed:在模式前面的每一行的末尾添加一些东西

时间:2017-04-24 09:29:20

标签: bash shell sed

我想在模式前面的每一行的末尾添加一个分号。 例如,我有以下文字:

          boxready: function() {
                Ext.select('.x-box-inner, .x-tab-center').selectable();
                var idVal = this.tab.btnEl.id;
                var button = document.getElementById(idVal);
                var height = button.style.height;
                var divEl = Ext.DomHelper.insertBefore(button, {       /*added a div in replacement of button*/
                    tag: 'div', 
                    id : idVal,
                    cls: 'RF_tabHeader x-tab-center',
                    title: button.title,
                    style: 'height: '+height
                });

                divEl.update(button.innerHTML);
                button.parentNode.removeChild(button);                 /* button tag is removed.*/
            }

我想有这个:

INSERT INTO line 1
INSERT INTO line 2
line 3
line 4
line 5
INSERT INTO line 6

我首先使用了sed命令:

INSERT INTO line 1;
INSERT INTO line 2
line 3
line 4
line 5;
INSERT INTO line 6;

但问题是我会在第2行的末尾有一个分号,而不是在第5行的末尾。 在INSERT INTO之前的每行结尾处自动执行此操作的解决方案是什么?这个文件包含数千个像这样的样本?

感谢您的时间!

1 个答案:

答案 0 :(得分:1)

1将文本存储到文件中:
cat data.txt
结果:

INSERT INTO line 1
INSERT INTO line 2
line 3
line 4
line 5
INSERT INTO line 6

2 awk脚本内容是:
cat awk.script
结果:

{
if (NR==1) {lastline=$0;}
if (NR>1 && $1 == "INSERT") {print lastline";";lastline=$0;} 
if (NR>1 && $1 != "INSERT") {print lastline;lastline=$0;}
}
END{if(lastline ~ /INSERT/) print lastline";";else print lastline; }

3执行awk命令:
awk -f awk.script data.txt
结果:

INSERT INTO line 1;
INSERT INTO line 2
line 3
line 4
line 5;
INSERT INTO line 6;
相关问题