I have a file that looks like this:
AE United Arab Emirates
AG Antigua & Barbuda
AN Netherlands Antilles
AS American Samoa
BA Bosnia and Herzegovina
awk '{ tmp = $1; sub(/^[^ ]+ +/, ""); print $0, tmp }'
If you're open to a Perl solution...
perl -lane 'print join " ",@F[1..$#F,0]' file
is a simple solution with an input/output separator of one space, which produces:
United Arab Emirates AE
Antigua & Barbuda AG
Netherlands Antilles AN
American Samoa AS
Bosnia and Herzegovina BA
Burkina Faso BF
Brunei Darussalam BN
This next one is slightly more complex
perl -F` ` -lane 'print join " ",@F[1..$#F,0]' file
and assumes that the input/output separator is two spaces:
United Arab Emirates AE
Antigua & Barbuda AG
Netherlands Antilles AN
American Samoa AS
Bosnia and Herzegovina BA
Burkina Faso BF
Brunei Darussalam BN
These command-line options are used:
-n
loop around every line of the input file, do not automatically print every line
-l
removes newlines before processing, and adds them back in afterwards
-a
autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace
-F
autosplit modifier, in this example splits on ' ' (two spaces)
-e
execute the following perl code
@F
is the array of words in each line, indexed starting with 0
$#F
is the number of words in @F
@F[1..$#F]
is an array slice of element 1 through the last element
@F[1..$#F,0]
is an array slice of element 1 through the last element plus element 0
awk '{ saved = $1; $1 = ""; print substr($0, 2), saved }'
Setting the first field to ""
leaves a single copy of OFS
at the start of $0
. Assuming that OFS
is only a single character (by default, it's a single space), we can remove it with substr($0, 2)
. Then we append the saved copy of $1
.
There's a sed option too...
sed 's/\([^ ]*\) \(.*\)/\2 \1/' inputfile.txt
Explained...
Swap
\([^ ]*\) = Match anything until we reach a space, store in $1
\(.*\) = Match everything else, store in $2
With
\2 = Retrieve $2
\1 = Retrieve $1
More thoroughly explained...
s = Swap
/ = Beginning of source pattern
\( = start storing this value
[^ ] = text not matching the space character
* = 0 or more of the previous pattern
\) = stop storing this value
\( = start storing this value
. = any character
* = 0 or more of the previous pattern
\) = stop storing this value
/ = End of source pattern, beginning of replacement
\2 = Retrieve the 2nd stored value
\1 = Retrieve the 1st stored value
/ = end of replacement
Yet another way...
...this rejoins the fields 2 thru NF with the FS and outputs one line per line of input
awk '{for (i=2;i<=NF;i++){printf $i; if (i < NF) {printf FS};}printf RS}'
I use this with git to see what files have been modified in my working dir:
git diff| \
grep '\-\-git'| \
awk '{print$NF}'| \
awk -F"/" '{for (i=2;i<=NF;i++){printf $i; if (i < NF) {printf FS};}printf RS}'
Another and easy way using cat command
cat filename | awk '{print $2,$3,$4,$5,$6,$1}' > newfilename