2

I have many lines like:

uid: jdoes mail:  jdoes@yahoo.com
mail:  mdoes@yahoo.com uid: mdoes
uid: kdoes mail:  kdoes@yahoo.com
mail:  tdoes@yahoo.com uid: tdoes

How do I rearrange them to look like :

uid: jdoes mail:  jdoes@yahoo.com
uid: mdoes mail:  mdoes@yahoo.com
uid: kdoes mail:  kdoes@yahoo.com
uid: tdoes mail:  tdoes@yahoo.com
  • uid: jdoes mail: jdoes@yahoo.com mail: mdoes@yahoo.com uid: mdoes uid: kdoes mail: kdoes@yahoo.com mail: tdoes@yahoo.com uid: tdoes How do I rearrange them to look like : uid: jdoes mail: jdoes@yahoo.com uid: mdoes mail: mdoes@yahoo.com uid: kdoes mail: kdoes@yahoo.com uid: tdoes mail: tdoes@yahoo.com – tester787 Aug 19 '16 at 23:14
  • 1
    Edit instead of commenting -- comments don't have enough formatting. And I'd use perl here. – Jeff Schaller Aug 20 '16 at 0:28
  • @JeffSchaller - Nah, perl was pretty much born from awk. Think of awk as perl -p <program>, although awk is slower in some cases. – grochmal Aug 20 '16 at 1:01
3

The backbone of AWK is to do something for a line that matches something. You have two types of lines therefore match each and print in a different way for each. One way to do it is:

awk '/^uid/ { print } /^mail/ { print $3" "$4" "$1"  "$2 }' <your files>

How does it work:

  • For lines starting with uid it prints them as they appear;
  • for lines starting with mail it arranges the columns differently (note the extra space between $1 and $2, since it is in there on the uid lines).

(This one is useful if you have other lines in the file.)


Another way:

awk '/^mail/{$0=$3" "$4" "$1" "$2};1' <your files>

How does it work:

  • print prints $0 (the full line) by default;
  • ;1 is equivalent to ; { print };
  • we change $0 for lines matching ^mail.

(This one is probably faster if you want to process and print all lines in the file. Thanks don_crissti.)

3

Task can be easy done with sed

sed 's/^\(mail:\s*\S*\)\s*\(.*\)/\2 \1/' file.lines

To be POSIX you should change \s to [[:blank:]] and \S to [^[:blank:]] or

sed 's/^\(mail:[^:]*\)[[:blank:]]\(.*\)/\2 \1/' file.lines

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.