LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   awk: swap fields given a condition (https://www.linuxquestions.org/questions/programming-9/awk-swap-fields-given-a-condition-836987/)

sebelk 10-08-2010 11:53 AM

awk: swap fields given a condition
 
Hi,

I have a file records as follows:

Jane pepe@pepe.biz
john@pepe.net John
Joe joe@willxyz.org

How can I get that always first field be given name and second one be the mail address?

I've tried

Code:

awk '$1 ~ /@/ { a=$1 ; $1=$2; $2=a; print  }'  file
But that doesn't worked

TIA

MensaWater 10-08-2010 12:19 PM

Not with awk but this little script would do it:

Code:

#!/bin/bash
while read first second
do if echo $first |grep \@ >/dev/null 2>&1
  then echo $second $first
  else echo $first $second
  fi
done

Just run the script with redirect in from file. So if you named the script "reorder.sh" you'd run it as:

Code:

reorder.sh <file
Where file is the name of the file with the original data. Should output:
Jane pepe@pepe.biz
John john@pepe.net
Joe joe@willxyz.org

GrapefruiTgirl 10-08-2010 01:09 PM

Here's a working fix-up of your awk code. I think the main problem with your original method was trying to assign values to fields, but you didn't tell us what exactly was happening when your code didn't work, so I'm guessing about that.

Anyhow, you don't need to assign anything to anything - just print the fields in the opposite order if the email address comes first; otherwise, print the record as it is:

Code:

awk '{ if ($1 ~ /@/){printf $2" "$1"\n"} else {print} }' filename
Best regards.

ghostdog74 10-08-2010 07:39 PM

Code:

awk '$1~/@/{t=$1;$1=$2;$2=t}1' file

GrapefruiTgirl 10-08-2010 07:49 PM

Thanks ghostdog74,

so what I see is:

OP had the exact right idea, only should have had the print statement outside the braces (where you've used a 1 instead)?

And, we can reassign fields to different values. I didn't know that!

Thanks,
Sasha

ghostdog74 10-08-2010 08:17 PM

Quote:

Originally Posted by GrapefruiTgirl (Post 4121990)
(where you've used a 1 instead)?

"1" is just a shortcut for print, i am sure you already know.

Quote:

And, we can reassign fields to different values. I didn't know that!
yes, but take note it will change the FS. Assign OFS if needed.


All times are GMT -5. The time now is 04:52 AM.