如何在awk中手动设置记录分隔符?

时间:2017-01-31 12:17:58

标签: awk

我有一个如下文件 -

vipin kumar ........................ kumar ......bangalore
    something something .......
;
vipin kumar ........................ kumar ......bangalore
    something something .......(testing
)
;
vipin kumar ......................... kumar .....bangalore
something something ;

我想要输出如下(名称和数字在文件中可以不同但唯一的共同点 - 当我们有&#34 ;;")

vipin kumar ........................ kumar ......bangalore   something something .......;
vipin kumar ........................ kumar ......bangalore    something something .......(testing);
vipin kumar ......................... kumar .....bangaloresomething something ;

I want to set the RS to ";" . 

我尝试了下面的命令 -

awk '{ORS=(NR%2==0?RS:FS)}1' file.txt

但是没有给出正确的输出,因为

NR%2 or NR%3无法工作,因为我不确定我将获得多少行;

然后我试图将RS设置为;使用下面的

awk '{for(i=1;i<=NF;i++) (ORS=(if($i ~ /;/?RS:FS);break}1' file.txt

但是这个命令不起作用。

4 个答案:

答案 0 :(得分:6)

<强>输入

$ cat f
vipin kumar ........................ kumar ......bangalore
    something something .......
;
vipin kumar ........................ kumar ......bangalore
    something something .......(testing
)
;
vipin kumar ......................... kumar .....bangalore
something something ;

<强>输出

$ awk 'ORS=/;/?RS:FS'  f
vipin kumar ........................ kumar ......bangalore     something something ....... ;
vipin kumar ........................ kumar ......bangalore     something something .......(testing ) ;
vipin kumar ......................... kumar .....bangalore something something ;

答案 1 :(得分:1)

我得到了答案,但可能有其他方法可以做到这一点。

awk '{for(i=1;i<=NF;i++) (ORS=($i ~ /;/)?RS:FS)}1' file.txt
vipin kumar ........................ kumar ......bangalore     something something ....... ;
vipin kumar ........................ kumar ......bangalore     something something .......(testing ) ;
vipin kumar ......................... kumar .....bangalore something something ;

答案 2 :(得分:1)

@VIPIN KUMAR:试试:

awk '/^vipin kumar/ && Q{print Q;Q=$0;next} {Q=Q?Q FS $0:$0} END{print Q}' Input_file

编辑:根据OP的要求,以下内容也有帮助。

awk '{printf("%s%s",$0,$0~/\;/?RS:"")}'  Input_file

答案 3 :(得分:1)

我的第一个目的是使用它:

awk '{gsub(/\n/,"",$0); printf "%s;\n", $0}'  ORS='\n' RS=\; a.txt

...但我真的很喜欢Akshay Hegde's answer