Unix/Linux Go Back    


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

UNIX for Dummies Questions & Answers


 
 
Thread Tools Search this Thread Display Modes
    #1  
Old Unix and Linux 08-17-2012   -   Original Discussion by beca123456
beca123456's Unix or Linux Image
beca123456 beca123456 is offline
Registered User
 
Join Date: Apr 2012
Last Activity: 17 March 2017, 3:18 PM EDT
Posts: 107
Thanks: 59
Thanked 0 Times in 0 Posts
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 Unix and Linux 08-17-2012   -   Original Discussion by beca123456
agama's Unix or Linux Image
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

Linux 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 06:31 PM
Field separator in awk aoussenko Shell Programming and Scripting 2 03-29-2010 01:59 PM
dynamically change awk Field Separator FS satnamx Shell Programming and Scripting 2 08-24-2009 07:51 PM
Change field separator of grep from : to space Jenny.palmy UNIX for Dummies Questions & Answers 2 06-09-2008 04:16 AM



All times are GMT -4. The time now is 01:54 PM.