Transcendental Llama
Transcendental Llama

Reputation: 45

awk multiple conditions output order

I'm trying to format a text file with awk. The text file looks something like this:

[----aaa1----]
**************************something1
**************************text1
**************************blabla1
[----aaa2----]
**************************something2
**************************text2
**************************blabla2
[----aaa3----]
**************************something3
**************************text3
**************************blabla3

I am using this awk command

awk 'NR % 4 == 1 {print | "rev | cut -c6- | rev | cut -c6-" } \
NR % 4 == 2 {print | "cut -c27-" } NR % 4 == 3 {print | "cut -c27-" } \
NR % 4 == 0 {print | "cut -c27-" }' so_test.txt

And I expect an output like this:

aaa1
something1
text1
blabla1
aaa2
something2
text2
blabla2
aaa3
something3
text3
blabla3

but instead I get this:

something1
text1
blabla1
something2
text2
blabla2
something3
text3
blabla3
aaa1
aaa2
aaa3

can someone please tell me why and how to fix it?

EDIT Let me clarify, the actual file I want to format is a few thousand lines long and the data differs from the one given as example. I can't filter by special characters, because the data in the file contains special characters and such. Basicaly every 4 lines follow this pattern

[92m/File/Path/here[00m
FileId                    0B01O-JsvW0LMDaI1B1RYOTQ1NVE  
ModTime                   2016-03-30 12:12:29 +0000 UTC 
LastModifyingUsername     User Name 

Upvotes: 1

Views: 141

Answers (2)

jijinp
jijinp

Reputation: 2662

with sed:

sed  -nr '1~4{s/^.{4}//;s/.{4}$//p};1~4!{s/^.{26}//p}' file

When line number is 1,5,9.. 1~4 remove first and last four characters from the line and print line. Else 1~4! remove first 26 characters from the line then print.

Upvotes: 0

fedorqui
fedorqui

Reputation: 289765

It might be better to use substr to print from a certain character:

awk 'NR%4==1{print substr($0,6, 4); next} {print substr($0, 27)}' file

This prints from the 6th character up to to the 10th when the line is on the form 4N+1. For the rest, it prints from the 27th until the end.

It returns:

aaa1
something1
text1
blabla1
aaa2
something2
text2
blabla2
aaa3
something3
text3
blabla3

From awk manual -> strings:

substr(string, start, length)

This returns a length-character-long substring of string, starting at character number start. The first character of a string is character number one. For example, substr("washington", 5, 3) returns "ing". If length is not present, this function returns the whole suffix of string that begins at character number start. For example, substr("washington", 5) returns "ington". This is also the case if length is greater than the number of characters remaining in the string, counting from character number start.

Upvotes: 3

Related Questions