使用 awk 使用多个分隔符分割并交换单词

问题描述 投票:0回答:1

如何用多个分隔符分割字符串,然后根据几个条件交换单词 -

来自字符串 - (分隔符是 _ 并且字符串可以随任何类型的单词而变化,而不仅仅是以 ocs 开头的字符串)

'customer_document_map_ocsumm2','customer_ocsumm1','session_detail_ocsumm2'

串起来 -

'ocsumm2.customer_document_map'::regclass,'ocsumm1.customer'::regclass,'ocsumm2.session_detail'::regclass

我用我对 awk 的最少知识尝试使用下面的代码,但徒劳无功,因为我不知道如何在每次拆分后存储结果,然后派生回所需的结果 -

awk 'BEGIN {
split($0,ary,",");
for(ele in ary){
    split(ele,ary2,"_")
    owner=ary2[$NF]     
}
print owner }'
awk
1个回答
0
投票
#/bin/sh -au

awk -vRS="," -vFS="_" -vORS=","  -vQ=\' '
{
  $0 = substr($0,2,length($0)-2)  # remove enclosing single quotes
  s=""
  for (i=1;i<NF;i++) { # accumulate fields, separated by unserscore, except last
    s = s "_" $i;
  }  # "s" ends up with a leading underscore, to be removed using substring
  print Q $NF "." substr(s,2)  Q "::regclass"
}' |
awk '{print substr($0,1,length($0)-1)}'  # remove trailing comma
  • RS为输入记录分隔符,默认换行,设置为逗号
  • FS 为输入字段分隔符,默认为空格,设置为下划线
  • ORS 为输出记录分隔符,默认换行,设置为逗号
  • Q 设置为单引号,因为它们在代码中逃脱是一场噩梦

脚本从标准输入读取并一一处理每个输入记录,重新组合字段以产生所需的输出。

© www.soinside.com 2019 - 2024. All rights reserved.