我有以下输入:
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做到这一点?
答案 0 :(得分:0)
使用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
答案 1 :(得分:0)
尝试:
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.
答案 2 :(得分:0)
awk -F\| '/Bash/{print $3"|"$2"|"$1}' file
cat|Bash|A
apple|Bash|C
email|Bash|D