0

I need to write a shell script where I have to create a duplicate record based on a condition and then change the value in a column of the new row which will be created.

I am trying to create a duplicate record based on a condition and then replace on column in the duplicate row.

Example:

Input will be

Col1,Col2,Col3,Col4,COl5

1234,abcd,abcd,wxyz,USD
2345,abcd,abcd,wxyz,USD
3456,abcd,abcd,wxyz,EUR

If the last column ie; col5 is EUR, then one more row should be created with change in column value.

Output should be

Col1,Col2,Col3,Col4,Col5

1234,abcd,abcd,wxyz,USD
2345,abcd,abcd,wxyz,USD
3456,abcd,abcd,wxyz,EUR
3456,abcd,abcd,wxyz,AUD
3

Here are a couple of ways:

  • awk

    awk -F, '{print; if($NF=="EUR"){$NF="AUD"; OFS=",";print}}' file
    

    That is checking the last field ($NR) to check another field, change $NR to $N, where N is the number you want to check (e.g $3 for the 5th field).

  • Perl

    perl -pe '$_.= "$1AUD\n" if /(.*)EUR$/' file 
    

    This one uses a lot of Perl shorthand that is kind of harder to explain. You can write the same thing like this:

    perl -e 'while(<>){if(/(.*)EUR$/){print "$_","$1AUD\n"} else {print "$_"}}' 
    

for each line of the input file

  • The perl one-liner will print the new record (with AUD) before the old one (with EUR) – Joseph R. Sep 23 '13 at 13:41
  • Thanks Joseph, Just to add, How can I change the position of condition column, FOr example if the condition column is Col3 instead of Col5. – Rakesh K Sep 23 '13 at 14:05
  • @user47766 see updated answer, the gawk one is easy to change, the Perl on is a bit more complex. – terdon Sep 23 '13 at 17:43
  • @user47766 Are we still talking about substituting EUR with AUD but a in a different column or will the patterns be different in this case? – Joseph R. Sep 23 '13 at 18:13
2

using sed:

 sed -e 's|^\(.*\),EUR$|\1,EUR\r\1,AUD|'
2

A Perl alternative

perl -ne 'print;print if s/EUR\Z/AUD/' your_file

If you want to make the modifications to the file in place, just add the -i switch:

perl -ni -e 'print;print if s/EUR\Z/AUD/' your_file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.