×
UNIX.COM Login
Username:
Password:  
Show Password






👤
Admin Notice


UNIX for Dummies Questions & Answers

This forum is closed for new posts. Please post beginner questions to learn unix and learn linux in this forum UNIX for Beginners Questions & Answers

change field separator only from nth field until NF

 

 
Thread Tools Search this Thread Display Modes
    #1  
Old 08-17-2012
beca123456 beca123456 is offline
Registered User
 
Join Date: Apr 2012
Last Activity: 6 July 2018, 2:55 PM EDT
Posts: 116
Thanks: 65
Thanked 1 Time in 1 Post
change field separator only from nth field until NF

Hi !

input:


Code:
111|222|333|aaa|bbb|ccc
999|888|777|nnn|kkk
444|666|555|eee|ttt|ooo|ppp

With awk, I am trying to change the FS "|" to "; " only from the 4th field until the end (the number of fields vary between records).

In order to get:


Code:
111|222|333|aaa; bbb; ccc
999|888|777|nnn; kkk
444|666|555|eee; ttt; ooo; ppp

I tried something like:


Code:
gawk 'BEGIN{FS=OFS="|"}{for(i=5; i<=NF; i++) $4 = $4 ($4?"; ":"")$i}1' input

It works for the 4th field, but it also prints the original fields from $5 to $NF after:


Code:
111|222|333|aaa; bbb; ccc|bbb|ccc
999|888|777|nnn; kkk|kkk
444|666|555|eee; ttt; ooo; ppp|ttt|ooo|ppp

Is there any way to to create an array from $4 until $NF without knowing the number of fields (a[$4...$NF])???

Thanks for your help !
Sponsored Links
    #2  
Old 08-17-2012
agama agama is offline
Registered User
 
Join Date: Jul 2010
Last Activity: 7 April 2014, 3:02 PM EDT
Location: earth>US>UTC-5
Posts: 1,466
Thanks: 110
Thanked 511 Times in 490 Posts
I think this is what you are looking for:



Code:
awk -F '|' '
    {
        for( i = 1; i < NF; i++ )
            printf( "%s%s", $(i), i > 3 ? ";" : "|" );
        printf( "%s\n", $(i) );
    }
' input-file >output-file

The Following User Says Thank You to agama For This Useful Post:
beca123456 (08-19-2012)
Sponsored Links
 

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

More UNIX and Linux Forum Topics You Might Find Helpful
Thread Thread Starter Forum Replies Last Post
awk, comma as field separator and text inside double quotes as a field. kevintse Shell Programming and Scripting 8 11-15-2010 05:31 PM
Field separator in awk aoussenko Shell Programming and Scripting 2 03-29-2010 12:59 PM
dynamically change awk Field Separator FS satnamx Shell Programming and Scripting 2 08-24-2009 06:51 PM
Change field separator of grep from : to space Jenny.palmy UNIX for Dummies Questions & Answers 2 06-09-2008 03:16 AM



All times are GMT -4. The time now is 04:57 AM.

Unix & Linux Forums Content Copyrightę1993-2018. All Rights Reserved.