Shell/Bash脚本每隔一列反转一次文本?

u4dcyp6a  于 2023-03-09  发布在  Shell
关注(0)|答案(2)|浏览(146)

我目前正在尝试编写一个bash/shell脚本,该脚本从.csv中提取数据,每隔一列反转所有字符串值,并输出到一个新的csv。我有一个脚本,该脚本每隔一列获取数据,但我不确定如何反转这些列中的字符串。

awk 'BEGIN{FS=","} {s=$NF; 
   for (i=1; i<=NF; i+=2) 
   printf ("%s%c", $i, i + 2 <= NF ? "," : "\n") 
}' input.csv > output.csv
h7wcgrx3

h7wcgrx31#

awk来救援!

$ seq 100 141 | pr -6ats, | 
  awk -F, 'function rev(x) {r=""; 
                            for(j=length(x);j;j--) r=r substr(x,j,1); 
                            return r}
           BEGIN {OFS=FS} 
                 {for(i=1;i<NF;i+=2) $i=rev($i)}1' 

001,101,201,103,401,105
601,107,801,109,011,111
211,113,411,115,611,117
811,119,021,121,221,123
421,125,621,127,821,129
031,131,231,133,431,135
631,137,831,139,041,141
egdjgwm8

egdjgwm82#

$ cat file
abc,def,ghi,klm

$ rev file
mlk,ihg,fed,cba

$ rev file |
  awk 'BEGIN{FS=OFS=","} NR==FNR{split($0,a); next} {for (i=1; i<=NF; i+=2) $i=a[NF-i+1]} 1' - file
cba,def,ihg,klm

相关问题