[英]How do I trim leading and trailing whitespace and replace it with tab(/t) to make it organized from each line of file?
我正在使用 Sun solaris 5.10。 在我的 shell 腳本中,我將 sql o/p 數據假脫機到 Unix 文件,稍后我使用該文件通過 mailx 發送郵件。 我的問題是 vim 或 cat unix 中的假脫機文件時,數據組織為 sql o/p。 然而,在將其重定向到郵件或將其復制到 word 文件中以檢查數據時,它變得雜亂無章。 我希望我的 o/p 與 sql o/p 的順序相同。
JOB_ID|JOB_NME |START_DTE_TIM |END_DTE_TIM |DURATION |STATUS
------------|------------------------------|------------------------------|----------------------|------------------------------|------------------------------
5|J191-JOB1 |18/08/2020 12:37:09 AM |18/08/2020 12:37:13 AM|4 Seconds |SUCCESS
4|J191-JOB12 |18/08/2020 12:37:09 AM | | |FAILED
1|J190-JOB3 |18/08/2020 12:37:10 AM |18/08/2020 12:37:14 AM|4 Seconds |SUCCESS
2|J190-JOB15 |18/08/2020 12:37:09 AM |18/08/2020 12:37:15 AM|6 Seconds |SUCCESS
我如何使用 awk、sed 或 trim 來實現它以使文件內容組織化。
有趣的是,第二行保留了列的大小。 所以你可以讀取文件的第二行並從中獲取列寬,然后使用寬度縮進所有其他列。
我將文件保存在名為a.txt
的文件中並執行了以下操作:
# Execute awk with | as separator
$ awk -F'|' '
# If first file and line number 2
FNR==NR&&NR==2{
# save the lengths of all fields in array named s
for (i=1;i<=NF;++i) s[i]=length($i)
}
# if the second file
FNR!=NR{
# for each field
for (i=1;i<=NF;++i) {
# print the field
# if the first field (i==1) then format the field to the right,
# otherwise to the left
# use the variable length %*s specifier to pass the length as parameter
printf("%" (i==1?"":"-") "*s%s",
# then lenght of the field
s[i],
# remove leftovers tabs and spaces in front and after values
gensub(/^[ \t]*([^ \t].*[^ \t])[ \t]*$/, "\\1", "1", $i),
# if its the last field, print a newline, otherwise print a |
i!=NF?"|":"\n");
}
# pass the file twice
}' a.txt a.txt
JOB_ID|JOB_NME |START_DTE_TIM |END_DTE_TIM |DURATION |STATUS
------------|------------------------------|------------------------------|----------------------|------------------------------|------------------------------
5|J191-JOB1 |18/08/2020 12:37:09 AM |18/08/2020 12:37:13 AM|4 Seconds |SUCCESS
4|J191-JOB12 |18/08/2020 12:37:09 AM | | |FAILED
1|J190-JOB3 |18/08/2020 12:37:10 AM |18/08/2020 12:37:14 AM|4 Seconds |SUCCESS
2|J190-JOB15 |18/08/2020 12:37:09 AM |18/08/2020 12:37:15 AM|6 Seconds |SUCCESS
另一個嘗試 solaris:
awk -F'|' '
FNR==NR&&NR==2{
for (i=1;i<=NF;++i) s[i]=length($i)
}
FNR!=NR{
for (i=1;i<=NF;++i) {
gsub(/^[ \t]*\([^ \t].*[^ \t]\)[ \t]*$/, "\\1", $i)
if (i == 1) { fmt = "%*s%s"; }
else { fmt = "%-*s%s"; }
printf(fmt, s[i], $i, i!=NF?"|":"\n");
}
}' a.txt a.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.