3

I have a file named input.txt which contains students data in StudentName|Class|SchoolName format.

Shriii|Fourth|ADCET
Chaitraliii|Fourth|ADCET
Shubhangi|Fourth|ADCET
Prathamesh|Third|RIT

I want to display this values in reverse order for particular college. Example:

ADCET|Fourth|Shriii
ADCET|Fourth|Chaitraliii

I used grep 'ADCET$' input.txt which gives output

Shriii|Fourth|ADCET
Chaitraliii|Fourth|ADCET

But I want it in reverse order. I also used grep 'ADCET$' input.txt | sort -r but didn't get required output

Ref1

SMshrimant
  • 638
  • 9
  • 15

1 Answers1

1

You may use either of the following sed or awk solutions:

grep 'ADCET$' input.txt | sed 's/^\([^|]*\)\(|.*|\)\([^|]*\)$/\3\2\1/'
grep 'ADCET$' input.txt | awk 'BEGIN {OFS=FS="|"} {temp=$NF;$NF=$1;$1=temp;}1'

See the online demo

awk details

  • BEGIN {OFS=FS="|"} - the field separator is set to | and the same char will be used for output
  • {temp=$NF;$NF=$1;$1=temp;}1:
    • temp=$NF; - the last field value is assigned to a temp variable
    • $NF=$1; - the last field is set to Field 1 value
    • $1=temp; - the value of Field 1 is set to temp
  • 1 - makes the awk write the output.

sed details

  • ^ - start of the line
  • \([^|]*\) - Capturing group 1: any 0+ chars other than |
  • \(|.*|\) - Capturing group 2: |, then any 0+ chars and then a |
  • \([^|]*\) - Capturing group 3: any 0+ chars other than|`
  • $ - end of line.

The \3\2\1 are placeholders for values captured into Groups 1, 2 and 3.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563