-1

Is it possible to move certain columns from one .txt file into another .txt file?

I have a .txt that contains:

USERID:ORDER#:IP:PHONE:ADDRESS:POSTCODE
USERID:ORDER#:IP:PHONE:ADDRESS:POSTCODE

With gawk I want to extract ADDRESS & POSTCODE columns into another .txt, so for this given file the output should be:

ADDRESS1:POSTCODE1
ADDRESS2:POSTCODE2

etc.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
wolf pkrs
  • 37
  • 1
  • 2
  • 8

3 Answers3

0

Try that:

awk -F: '{printf "%s:%s ",$5,$6}' ex.txt

input is

USERID:ORDER#:IP:PHONE:ADDRESS1:POSTCODE1
USERID:ORDER#:IP:PHONE:ADDRESS2:POSTCODE2

output is (on one line if I understand correctly)

ADDRESS1:POSTCODE1 ADDRESS2:POSTCODE2

only default is that it ends with a trailing space and does not end with a newline.

Which can be fixed with the slightly more complex (but still readable):

  awk -F: 'BEGIN {z=0;} {if (z==1) { printf " "; } ; z=1; printf "%s:%s",$5,$6} END{printf"\n"}' ex.txt
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • Quick question, how do I specify which .txt file for the program to use.. or is ex.txt the input file & not the output? – wolf pkrs Aug 20 '16 at 14:16
  • `ex.txt` is the input. To redirect to a file just add `> out.txt` in the end. – Jean-François Fabre Aug 20 '16 at 14:18
  • error, gawk: 'BEGIN gawk: ^ invalid char ''' in expression – wolf pkrs Aug 20 '16 at 14:22
  • works fine here on MSYS or DOS CMD.exe. Have you tried both solutions? which one fails for you? I'm using GNU Awk 4.1.3. Can you type `gawk --version` and tell me the result. – Jean-François Fabre Aug 20 '16 at 14:31
  • I have 3.1.6 atm :/ – wolf pkrs Aug 20 '16 at 14:35
  • nothing fancy in my awk code. Are you running from a windows terminal? MSYS? Linux ? Can you upgrade? and tell us what the caret points to (`^`) in the above message (the line above we don't have). You can also put the expression between simple quotes in a file and use `-f` option instead of passing the whole command as a parameter. – Jean-François Fabre Aug 20 '16 at 14:43
  • im using a .bat filon windows, uhm i can't seem to find a version of 4.1.3 – wolf pkrs Aug 20 '16 at 14:58
  • Atandard advice in Windows is to put the awk script in a file and execute it as `awk -f script` to avoid Windows quoting hell. Better yet - install/use cygwin. – Ed Morton Aug 20 '16 at 17:44
  • Thank you everyone for the support, @Jean-FrançoisFabre your script works :) & Ed Morton thank you for cygwin, that was the solution i needed. – wolf pkrs Aug 20 '16 at 18:06
0

This is a classic AWK transform. You want to use "-F :" to specify that the input is delimited by ":" and print a new ":" on output:

awk -F: '{ print $5 ":" $6 }' <input.txt >output.txt
TomOnTime
  • 4,175
  • 4
  • 36
  • 39
0
awk -F: 'NR==1 {print $5"1:"$6"1"};NR==2 {print $5"2:"$6"2"}' file
ADDRESS1:POSTCODE1
ADDRESS2:POSTCODE2
Claes Wikner
  • 1,457
  • 1
  • 9
  • 8