2

I have many lines like:

uid: jdoes mail:  [email protected]
mail:  [email protected] uid: mdoes
uid: kdoes mail:  [email protected]
mail:  [email protected] uid: tdoes

How do I rearrange them to look like :

uid: jdoes mail:  [email protected]
uid: mdoes mail:  [email protected]
uid: kdoes mail:  [email protected]
uid: tdoes mail:  [email protected]
3

2 Answers 2

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.)

0
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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .