2

I am using Twitter to pull news into an email, and the last six fields are the date and time. I would like these to be the first six fields. What's the command in awk to move the last n fields to the start of the line?

I have tried googling it but all the examples given assume each line has the same number of fields

example:

76356378090986
08976357627980089
089723571237809209
0897253712730912838798
908916523568909887
876756467890
09876535467890
765643324343
467890876543
234567890987654
123456789009876543
54323456789876
09876543345678
123456789009876
12345678998765

result:

09098676356378
98008908976357627
809209089723571237
8387980897253712730912
909887908916523568
467890876756
46789009876535
324343765643
876543467890
987654234567890
876543123456789009
78987654323456
34567809876543
009876123456789
99876512345678
7

With sed:

sed 's/\(.*\)\(.\{6\}\)/\2\1/'
5

With sed:

sed -E 's/(.*)(.{6})/\2\1/'

Or:

sed 's/\(.*\)\(.\{6\}\)/\2\1/'

With awk:

awk '{l=length-6;print(substr($0,l+1) substr($0,1,l))}'

With (GNU) awk:

awk '{print gensub(/(.*)(.{6})/,"\\2\\1",1)}'
1
cat file | sed -e 's/\(.\)/\1 /g' | awk '{ for (i = 1; i <= NF; i++) printf "%s" FS, $((NF-7+i) % NF+1); print ""}' | sed 's/ //g'
09098676356378
98008908976357627
809209089723571237
8387980897253712730912
909887908916523568
467890876756
46789009876535
324343765643
876543467890
987654234567890
876543123456789009
78987654323456
34567809876543
009876123456789
99876512345678
  • that's a clear example of [Humor] Useless use of cat. sed is able to read a file. Having used awk, why also call sed (twice)? – Isaac Oct 8 '18 at 12:09
0

A couple of perl one-liners:

  1. splitting each line into characters:

    perl -F'' -lane 'print join "", splice(@F, -6), @F' file
    
  2. using substrings

    perl -lpe '$_ = substr($_, -6) . substr($_, 0, $#_ - 6)' file
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy