awk - Awk printf to fix date slashes
问题描述
How do I remove the "/" from field $1 in this input file for an awk command? I will be printing this field as the last field. Here is my input file.
05/14/2021,63,131629,508138,JOSHUA KATENBRINK,85.91,CHECK,775,90131629
05/14/2021,63,107001,504026,JOHN JONES,54.62,CHECK,1354,90107001
05/14/2021,63,105071,502632,STEPHANIE WATSON,64.00,CHECK,2210,90105071
05/14/2021,63,103202,501333,CURD MARTIN INC,63.74,CHECK,5129,90103202
05/14/2021,63,103202,501332,CURD MARTIN INC,112.11,CHECK,5129,90103202
I tried using this but it reduces the output to "2" for field $1.
gsub(///,"",$1)
Update: I have added my awk script here for more clarity. I'm sure my liberal use of that silly "outspacer" variable is not the best choice! However, it works, so I'm trying to focus more on the slashes in the date field. And the gsub to eliminate the decimal in field $6 also fails. FYI, I am using gawk in Windows 10 using the Ubuntu Linux subsystem. Not sure if that's the reason for the escapes failing.
BEGIN{
FS=","
RS="\r\n"};
{
outspacer = " ";
printf("%3s%-14s%-30s%010.2f%-16s%-9s%-20s%-92s%9s%1s%-8s%-47s\r\n",outspacer, $2, $4, gsub(".","",$6), $8, outspacer, $5,outspacer, $9,outspacer,gsub("/","",$1),outspacer);
}
解决方案
You can use
awk -F, '{outspacer = " ";a=$1;b=$6;gsub("/", "", a);gsub(/\./, "", b);printf("%3s%-14s%-30s%010d %-16s%-9s%-20s%-92s%9s%1s%-8s%-47s\r\n",outspacer, $2, $4, b, $8, outspacer, $5, outspacer, $9, outspacer, a, outspacer)}' file
Note that gsub
does not return the modified string, it actually modifies the $1
value.
Thus, to actually be able to use a modified $1
, you can assign it to a variable, say, a
, and then modify it with a gsub
.
Here, a=$1;gsub("/", "", a);
is used to set the value of Field 1 to a
variable, then /
are removed, and then a
is used in the printf
command.
With GNU awk
, you may also use gensub
the way you were doing:
awk -F, '{outspacer=" ";printf("%3s%-14s%-30s%010d %-16s%-9s%-20s%-92s%9s%1s%-8s%-47s\r\n",outspacer, $2, $4, gensub(/\./,"","g",$6), $8, outspacer, $5,outspacer, $9,outspacer, g
ensub("/","","g", $1),outspacer)}' file
Here, gensub("/", "", "g", $1)
replaces all occurrences of a slash in Field 1 with an empty string and returns the updated value of the first field. gensub(/\./,"","g",$6)
removes all dots in Field 6.
推荐阅读
- angular - Angular Observable 取消订阅在哪里?
- maxima - wxMaxima 断言失败:“lang == wxLANGUAGE_DEFAULT”
- mxgraph - mxClient 将不同的形状全部呈现为正方形
- xpages - JSPDF-autotable : jsPDF 未定义
- google-bigquery - 尝试将纪元代码字段(字符串类型)转换为时间戳
- python - 我不能让 return 和 print (Python) 一样
- angular - 从可观察的“同步”访问返回对象
- java - 自动完成下拉选择
- octobercms - registerMailPartials() 和 registerMailLayouts()
- curl - 通过 cURL 远程触发 Maven 发布