简体   繁体   中英

awk print the number of columns between a selected range from awk

  1. I have the next line for show a range of text from file. It's correct, but i would like to show the number of line at the first of each line. I prove with different s options without results.
    buffer=`awk -v desde="$DESDE" -v hasta="$HASTA" 'NR>=desde&&NR<=hasta' "$FICH"

The output of the command below is the next:

1:20220413:20:Curso Astrología:5:Vicente Ferrer

1:10042022:0:Donación instituto Samye:103:Propia

14:20220428:0:Candelario Yeshe Nyimpo Inc:9:Dudjom Tersar

1:20220512:60:Ayuda por el Hambre y Violencia:6:Vicente Ferrer

 Total Lineas: 43 | Total Pag: 2  |Buffer: De 0  hasta 26 | 27

But i would like the next result:

1 1:20220413:20:Curso Astrología:5:Vicente Ferrer

2 1:10042022:0:Donación instituto Samye:103:Propia

3 14:20220428:0:Candelario Yeshe Nyimpo Inc:9:Dudjom Tersar

4 1:20220512:60:Ayuda por el Hambre y Violencia:6:Vicente Ferrer

 Total Lineas: 43 | Total Pag: 2  |Buffer: De 0  hasta 26 | 27

Thank you in advanced

1st solution: With your shown samples please try following awk code. I have improved your attempted code, also taken care in case line number crosses hasta value it will simply exit from program to save some cycles and time.

awk -v desde="$DESDE" -v hasta="$HASTA" '
NR>hasta{ exit }
NR>=desde && NR<=hasta{
  if(/^ Total/ || !NF){print; next }
  if(NF){print ++count,$0}
}
' "$FICH"


2nd solution with your shown output run following on your shown output in case you want to do so:

awk '/^ Total/ || !NF{print;next} NF{print ++count,$0}' Input_file

Explanation: Adding detailed explanation for above code.

awk '                 ##Starting awk program from here.
/^ Total/ || !NF{     ##Checking condition if line starts from space Total OR its NULL then.
  print               ##Print that line.
  next                ##next will skip all statements from here.
}
NF{                   ##Checking condition if NF is NOT NULL for current line then:
  print ++count,$0    ##Printing count value(increasing it with 1 before printing) followed by current line value.
}
' Input_file          ##Mentioning Input_file name here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM