Home > Blockchain >  Grep to select alternate outputs after certain Characters
Grep to select alternate outputs after certain Characters

Time:04-17

I have a text file test.txt

It has list as follows
Profile Roy
 City: New York
 Age: 78_months
 Sex: Male
Profile Smith
 City: Texas
 Age: 56_months
 Sex: Male

What I want is to grep output of Roy and Smith and so on so forth...... such that it should output as

78_months New York
56_months Texas

What I tried so far didn't work

grep -l 'Age:|City:' test.txt >> output txt

CodePudding user response:

A twisted solution: convert the input to YAML then process it with yq.

sed -E 's/^(Profile)/- \1:/; s/^  /  /' test.txt |
yq eval '.[] | .Age   " "   .City'
78_months New York
56_months Texas

CodePudding user response:

I would not use grep here, look into sed or awk ..

example for awk/sed well haven't used them in a while ..

Person Name
123 High Street
(222) 466-1234

Another person
487 High Street
(523) 643-8754


$ awk 'BEGIN{FS="\n"; RS=""} {print $1,$3}' addresses

will output

Person Name (222) 466-1234
Another person (523) 643-8754

so awk '/Age|City/,1' will output

 
 City: New York
 Age: 78_months
 City: Texas
 Age: 56_months

Then awk awk '{x = $0; getline; print; print x}'

will switch lines to

 Age: 78_months
 City: New York
 Age: 56_months
 City: Texas

so a quickhack is

awk '/Age|City/,1' test | awk '{x = $0; getline; print; print x}' | sed -r 's/Age://g' | sed -r 's/City://g' | xargs -n2 | sed 's/ */ /g'

:P

78_months New York
56_months Texas

CodePudding user response:

Suggesting awk script:

 awk '{print $5, $3}' RS="Profile" FS="[:\n]" input.1.txt

Output for provided input:

$ awk '{print $5, $3}' RS="Profile" FS="[:\n]" input.1.txt
 
 78_months  New York
 56_months  Texas

Explanation:

{print $5, $3} Print 5th field and 3rd field following by newline.

RS="Profile" Set awk record separator to RegExp "Profile"

FS="[:\n]" Set awk field separator to char : and newline \n

  • Related