jaypal singh
jaypal singh

Reputation: 77185

Using awk to format the output

I have a significantly large string that that I need to format so that no more than 16 bytes are shown on each line. I used the for loop to go up 16 bytes but then the script stops parsing the remaining string. I need to add a new line after 16th byte so that then next 16 bytes continue on the next line.

$ echo "45a000531ee1000036118b9472041523cb5c8701084b084b003ff3443213002f8445f0a4a3d7000001800e291053dbe7157faa3ea02f850004720415238500047cc3685387000c020b921f7196979774f9000000" 
|  sed 's/../ &/g' | sed 's/^ //' 
| awk 'ORS="\n"{ for (i=1; i<17;i++) printf ("%s ", $i)}'
45 a0 00 53 1e e1 00 00 36 11 8b 94 72 04 15 23

Solution: (Courtesy: Chris)

awk 'NF{gsub(/.{16}/,"&\n",$0);print $0}' text | sed 's/../ &/g' | sed 's/^ //g'    
45 a0 00 53 1e e1 00 00    
36 11 8b 94 72 04 15 23    
cb 5c 87 01 08 4b 08 4b     
00 3f f3 44 32 13 00 2f     
84 45 f0 a4 a3 d7 00 00     
01 80 0e 29 10 53 db e7     
15 7f aa 3e a0 2f 85 00     
04 72 04 15 23 85 00 04      
7c c3 68 53 87 00 0c 02      
0b 92 1f 71 96 97 97 74      
f9 00 00 00

Upvotes: 0

Views: 276

Answers (2)

ninjalj
ninjalj

Reputation: 43748

fold folds long lines:

fold -b16 | sed 's/../& /g'

Upvotes: 2

Chris
Chris

Reputation: 3047

try:

command:

echo "yourLongString" | sed 's/.\{16\}/&\n/g' 

output:

45a000531ee10000
36118b9472041523
cb5c8701084b084b
003ff3443213002f
8445f0a4a3d70000
01800e291053dbe7
157faa3ea02f8500
0472041523850004
7cc3685387000c02
0b921f7196979774
f9000000

EDIT:

Or with gawk:

gawk 'NF{gsub(/.{16}/,"&\n",$0);print $0}'

HTH Chris

Upvotes: 4

Related Questions