Awk - сохранение строк из файла в переменные - PullRequest
1 голос
/ 25 февраля 2020

не могли бы вы помочь мне со скриптом bash / awk? У меня есть несколько файлов .dat в каталоге. Все эти файлы состоят из заголовка и данных:

c ROIysiz= 28
c column1= HJD
c RedNumDa= 18262
c column3= ERROR
c column2= FLUX
c end header ---------------------------------------------------------------------------------------
2.458375368952875026e+06 -8.420548421860798386e-04 7.020812100561693928e-03
2.458375579737625085e+06 -5.579159672996818198e-03 1.285380720081348528e-03
2.458376278315599542e+06 -7.634101850411220518e-03 2.481065693991901019e-03
2.458376347386624664e+06 7.223482191697593166e-04 2.319993894372075760e-03
2.458376416108166799e+06 5.238757879614985152e-03 1.389030320490110878e-03
2.458376485913363751e+06 6.777606553373448882e-03 8.887787066666734273e-04
2.458377048675692175e+06 1.950435173388009522e-02 3.242344477396308117e-03
2.458377185153110884e+06 1.885754079806525874e-02 2.090836971653367571e-03

filename - Old-file Я хотел бы для всех файлов:

1) сохранить имя файла в переменной

2) для сохранения некоторой информации из заголовка в переменные - например, строка после "c column3 =", "c column2 =" и "c ROIysiz ="

3) используя переменные с сохраненной информацией из заголовка, я бы хотел переименовать файл - например, "FLUX28"

4) создать новый файл

5) для печати информации из переменных в первую строку нового файла - например, имя файла исходного файла, информация после "c column3 =", "c column2 ="

6) печать данных - печать детали исходного файла после начала строки "c end header"

7) добавить # в начало первой строки

#!/bin/bash
for file in *.dat; do                   # loop in the directory
awk -v FILE=$FILE_NAME                  # save file name to variable FILE

/c end header/ { in_f_format=0; next }  # print file from c end header

{print $1, $2, $3}                      # print columns

BEGIN{printf("#")}1                     # adding hashtag before the first line
; done                                  # end of loop

желаемый вывод

файлы с именами FLUX28

(в другом файле будет другой номер - имя файла будет состоит из строк из заголовка) в файлах будет:

#Old-file ERROR FLUX
2.458375368952875026e+06 -8.420548421860798386e-04 7.020812100561693928e-03
2.458375579737625085e+06 -5.579159672996818198e-03 1.285380720081348528e-03
2.458376278315599542e+06 -7.634101850411220518e-03 2.481065693991901019e-03
2.458376347386624664e+06 7.223482191697593166e-04 2.319993894372075760e-03
2.458376416108166799e+06 5.238757879614985152e-03 1.389030320490110878e-03
2.458376485913363751e+06 6.777606553373448882e-03 8.887787066666734273e-04
2.458377048675692175e+06 1.950435173388009522e-02 3.242344477396308117e-03
2.458377185153110884e+06 1.885754079806525874e-02 2.090836971653367571e-03

Код из обсуждения:

awk '
/ROIysiz/{
second_out=$NF
}
/column 3/{
third_part=$NF
}
/column2/{
close(out_file)
found=count=""
out_file=$NF second_out third_part
next
}
/end header/{
found=1
next
}
found && out_file{
if(++count==1){
print "#" $0 > (out_file)
}
else{
print > (out_file)
}
}
' input

1 Ответ

1 голос
/ 25 февраля 2020

Не могли бы вы попробовать следующие, не проверенные полностью.

awk '
/ROIysiz/{
  second_out=$NF
}
/column2/{
  close(out_file)
  found=count=""
  out_file=$NF second_out
  next
}
/end header/{
  found=1
  next
}
found && out_file{
  if(++count==1){
    print "#" $0 > (out_file)
  }
  else{
    print > (out_file)
  }
}
' Input_file

Объяснение: Добавлено подробное объяснение вышеприведенного кода.

awk '                          ##Starting awk program from here.
/ROIysiz/{                     ##Checking condition if a line contains string ROIysiz then do following.
  second_out=$NF               ##Creating variable second_out for output file 2nd part.
}
/column2/{                     ##Checking condition if line contains column2 string in it.
  close(out_file)              ##Closing out_file to avoid "too many files opened" error.
  found=count=""               ##Nullifying variable found here.
  out_file=$NF second_out      ##Creating variable out_file which is having last field of current line and second_out variable value.
  next                         ##next will skip all further statements from here.
}
/end header/{                  ##Checking condition if string end header is found then do following.
  found=1                      ##Setting variable found to 1 here.
  next                         ##next will skip all further statements from here.
}
found && out_file{             ##Checking condition if found AND out_file is SET then do following.
  if(++count==1){              ##If count==1 then do following, to add # in starting of first line.
    print "#" $0 > (out_file)  ##Printing # and current line to out_file now.
  }
  else{                        ##Else if count is greater than 1 then do following.
    print > (out_file)         ##Printing current line to out_file here.
  }
}
' Input_file                   ##Mentioning Input_file name here.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...