如果匹配,如何使用awk或其他工具重新排列字段

如果匹配,如何使用awk或其他工具重新排列字段,awk,field,match,Awk,Field,Match,我有一个lisp程序输出的文件: (john (a b c (grade 90 good))) (doe (e f (grade 80 fair) g h i j)) (mary ((grade 100 best)) (jane (x y (grade 95 better) z)) 我想把(年级编号说明)移到名字的右边;e、 g (john (grade 90 good) (a b c)) (doe (grade 80 fair) (e f g h i j)) 这就是我所拥有的,但它是

我有一个lisp程序输出的文件:

(john (a b c (grade 90 good)))
(doe  (e f (grade 80 fair) g h i j))
(mary ((grade 100 best))
(jane (x y (grade 95 better) z))
我想把(年级编号说明)移到名字的右边;e、 g

(john (grade 90 good) (a b c))
(doe  (grade 80 fair) (e f g h i j))

这就是我所拥有的,但它是丑陋的代码,并没有像上面那样给我想要的干净的结果;有人能帮忙吗?谢谢

cat studentGrades | sed 's/[()]/ /g' | awk 
'{ if (/grade/)  
      {for (i=1;i<=NF;++i) 
           {if ($i=="grade") 
               {printf ("%s ( %s %s %s ) %s\n",$1, $i, $(i+1), $(i+2), $0)}}}  
   else {print $0} 
}'
cat学生成绩| sed's/[()]//g'| awk
{if(/grade/)

{对于(i=1;i也许您可以使用:

awk -F'[()]' '{printf "(%s(%s)(%s%s))\n", $2, $4, $3, $5}' file
sed 's/\(([^(]*\)\((.*\)\((grade[^)]*)\)\(.*\)/\1\3\2\4/' file
输出:

(john (grade 90 good)(a b c ))
(doe  (grade 80 fair)(e f  g h i j))
(mary (grade 100 best)())
(jane (grade 95 better)(x y  z))

输入字段分隔符设置为
。其余的只是重新排列字段的情况。

在您的示例中,第3行中的括号没有配对。我假设缺少一个结尾
。我在测试中修复了它。(见下文)

这个sed一行应该可以,它将保持第三行不变,因为描述是空的

sed 's/\(([^(]*\)\((.\+\)\((grade[^)]*)\)\(.*\)/\1\3\2\4/' file
如果仍要“移动”空描述,请使用以下命令:

awk -F'[()]' '{printf "(%s(%s)(%s%s))\n", $2, $4, $3, $5}' file
sed 's/\(([^(]*\)\((.*\)\((grade[^)]*)\)\(.*\)/\1\3\2\4/' file
用您的示例测试

kent$  cat f
(john (a b c (grade 90 good)))
(doe  (e f (grade 80 fair) g h i j))
(mary ((grade 100 best)))  <<<<<<<<- here I added a ")"
(jane (x y (grade 95 better) z))
第二个一号班轮:

kent$  sed 's/\(([^(]*\)\((.\+\)\((grade[^)]*)\)\(.*\)/\1\3\2\4/' f
(john (grade 90 good)(a b c ))
(doe  (grade 80 fair)(e f  g h i j))
(mary ((grade 100 best)))
(jane (grade 95 better)(x y  z))
kent$  sed 's/\(([^(]*\)\((.*\)\((grade[^)]*)\)\(.*\)/\1\3\2\4/' f
(john (grade 90 good)(a b c ))
(doe  (grade 80 fair)(e f  g h i j))
(mary (grade 100 best)())
(jane (grade 95 better)(x y  z))

我给出了这个
+1
,因为它很容易阅读和理解。sed
解决方案不是。