Отображение каждой разделенной полем строки в обратном порядке полей - PullRequest
0 голосов
/ 20 января 2019

У меня есть следующий вход :

A|Bash|cat
B|bit|dog
C|Bash|apple
D|Bash|email

Я хочу следующий вывод :

cat|Bash|A
apple|Bash|C
email|Bash|D

Идея состоит в том, чтобы отобразить все те строки, которые содержат «Bash», и отобразить их поля в обратном порядке.

Я могу отобразить эти строки в прямом порядке, используя awk:

$ awk '/Bash/' filename.txt

Но я не могу отобразить его в обратном порядке. Есть ли способ сделать это с помощью awk?

Ответы [ 3 ]

0 голосов
/ 20 января 2019

попробовать:

awk -F \| '/Bash/{for(i=NF;i>1;i--){printf("%s|",$i);}print $1}' filename.txt

где:

    -F \| - sets the delimiter
    /Bash/ - searching the text you want. (to be more precise you should do $2==/Bash/)
    for - loop from NF which is number of fields. here NF=3. to one above 1.
    printf = to print token i, and add the delimiter
    print - outside the loop, printing the first token. this is outside the loop to avoid having the delimiter "|" as the last character printed.
0 голосов
/ 22 января 2019
awk -F\| '/Bash/{print $3"|"$2"|"$1}' file 
cat|Bash|A
apple|Bash|C
email|Bash|D
0 голосов
/ 20 января 2019

Использование GNU awk:

$ awk '
BEGIN { 
    FS=OFS="|"                            # set the delimiters
    k="Bash"                              # set the keyword
}
$2==k {                                   # if keyword in 2nd field
    a[$1]=$3                              # hash $3 and index with 1st field
}
END {
    PROCINFO["sorted_in"]="@ind_str_asc"  # control the for traverse order
    for(i in a)                           # loop
        print a[i],k,i                    # ... and output
}' file
cat|Bash|A
apple|Bash|C
email|Bash|D
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...