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 TIA |
Not with awk but this little script would do it:
Code:
#!/bin/bash Code:
reorder.sh <file Jane pepe@pepe.biz John john@pepe.net Joe joe@willxyz.org |
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 |
Code:
awk '$1~/@/{t=$1;$1=$2;$2=t}1' file |
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 |
Quote:
Quote:
|
All times are GMT -5. The time now is 04:52 AM. |