Используйте awk, чтобы сопоставить и сохранить, добавить шаблон, а также разбить строку с разделителем - PullRequest
0 голосов
/ 02 июня 2018

У меня нижеприведенный вывод из текстового файла, который мне нужно отформатировать, чтобы сделать его более читабельным.

julian text:case2345
maria  text:case4567
clover text,text,text,text,text,text:case3456
neil   text,text:case09876

Мне нужно переформатировать вывод следующим образом:

julian text:case2345
maria  text:case4567
clover text:case3456 
clover text:case3456
clover text:case3456
clover text:case3456
clover text:case3456
clover text:case3456
neil   text:case09876
neil   text:case09876

Используя awk, я пытался сопоставить регистр шаблона [0-9], сохранить его в переменной, а затем разделить строку с помощью разделителя "," и, наконец, напечатать.Я пытался ниже ниже, но не смог получить желаемый результат

awk '/match($0,/case[0-9]/){val=substr($0,RSTART,RLENGTH);next}{split($2,k,","); for (i in k) {printf ("%s %s %s\n\n",$1,k[i],val)}}'

Ответы [ 3 ]

0 голосов
/ 02 июня 2018

После awk может помочь здесь.(Учитывая, что ваш действительный файл Input_file является показанным примером).

awk -F' +|,|:' '$NF~/[cC][aA][sS][eE]/ && NF>2{for(i=2;i<=(NF-1);i++){print $1 OFS $i":"$NF};next} 1' Input_file

Добавление решения с не одним вкладышем тоже сейчас.

awk -F' +|,|:' '
$NF~/[cC][aA][sS][eE]/ && NF>2{
  for(i=2;i<=(NF-1);i++){
    print $1 OFS $i":"$NF};
  next
}
1
'  Input_file

Объяснение: Добавление пояснения к коду теперь тоже.

awk -F' +|,|:' '           ##Setting field separator as space(s) OR comma OR colon here for each line.
$NF~/[cCaAsSeE]/ && NF>2{  ##Checking condition here if last field is having case OR CASE string in it and number of fields are more than 2.
  for(i=2;i<=(NF-1);i++){  ##Starting a for loop which starts from 2nd value to second last value of total fields value here.
    print $1 OFS $i":"$NF};##first field OFS(whose default value is space) value of current field and colon with last field of line.
  next                     ##next is awk default keyword which will skip all further lines now.
}
1                          ##Only those lines will come here which was NOT true for above conditions, simple printing of line will happen here.
' Input_file               ##Mentioning Input_file name here.
0 голосов
/ 02 июня 2018

Просто подправьте ответ на свой предыдущий вопрос :

$ awk -F'[ ,:]+' '{for (i=2;i<NF;i++) print $1, $i ":" $NF}' file
julian text:case2345
maria text:case4567
clover text:case3456
clover text:case3456
clover text:case3456
clover text:case3456
clover text:case3456
clover text:case3456
neil text:case09876
neil text:case09876
0 голосов
/ 02 июня 2018
# set field separator
awk -F '[: ]+' '/,/{                                # if line/row/record contains comma 
                    split($2,arr,/,/);              # split 2nd field by comma, 
                                                    # store elements in array arr
                    for(i=1; i in arr;i++)          # iterate through array arr
                         print $1, arr[i] ":" $NF;  # print 1st field, array element and last field from record
                    next                            # stop processing go to next line
                                                    # 1 at the end does default operation that is print $0
                }1' infile

Результаты теста:

$ cat infile
julian text:case2345
maria  text:case 4567
clover text,text,text,text,text,text:case3456
neil   text,text:case09876

$ awk -F '[: ]+' '/,/{split($2,arr,/,/);for(i=1; i in arr;i++)print $1,arr[i]":"$NF;next}1' infile
julian text:case2345
maria  text:case 4567
clover text:case3456
clover text:case3456
clover text:case3456
clover text:case3456
clover text:case3456
clover text:case3456
neil text:case09876
neil text:case09876
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...