VIPIN KUMAR
VIPIN KUMAR

Reputation: 3147

How to manually set the record seperator in awk?

I have a file like below -

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

I want the output like below ( name and number can be different in the file but the only thing that is common - line is ending when we have ";")

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 ";" . 

I tried below commands -

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

but it is not giving the correct output because

NR%2 or NR%3 won't work as i am not sure after how many lines i will get ;

then i tried to set the RS to ; using below

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

But this command is not working.

Upvotes: 4

Views: 263

Answers (4)

hek2mgl
hek2mgl

Reputation: 158110

My first intention was to use this:

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

... but I really like Akshay Hegde's answer.

Upvotes: 1

Akshay Hegde
Akshay Hegde

Reputation: 16997

Input

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

Output

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

Upvotes: 7

RavinderSingh13
RavinderSingh13

Reputation: 133650

@VIPIN KUMAR: Try:

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

EDIT: As per OP's requirement following could help too.

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

Upvotes: 2

VIPIN KUMAR
VIPIN KUMAR

Reputation: 3147

I got the Answer, but there may be other way to do that.

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 ;

Upvotes: 1

Related Questions