Scripting in Bash

China☆狼群 提交于 2020-01-07 00:33:49

问题


I have a function in bash say parse which takes one argument and function name is f. My file to be processed is somewhat like

a@b@c@
a@d@e@g@
m@n@
t@

I want to give the output as

a@f(b)@f(c)@
a@f(d)@f(e)@f(g)@
m@f(n)@
t@

That is apply function f to all except the first. Any clues so how can I do this?


回答1:


maybe this is what you want?

e.g. you have a script called sqr.sh:

kent$  cat sqr.sh
#!/bin/bash
echo $(($1*$1))

now you want to apply the function above on your input:

kent$  echo "foo@2@3@4@
0@10@20@
x@"|awk -F'@' -v OFS=@ '{for(i=2;i<=NF;i++) if($i) "./sqr.sh "$i|getline $i; print}'

foo@4@9@16@
0@100@400@
x@



回答2:


This should do it:

sed 's/@\([^@]*\)/@f(\1)/g'

If all the fields are single characters, you can simplify it a bit (say, using . rather than \([^@]*\)).




回答3:


You could use sed:

sed -e 's/@\(.\)/@f(\1)/g'



回答4:


awk 'BEGIN {OFS=FS="@"} {for (i=2; i<=NF-1; i++) $i="f("$i")"; print}'


来源:https://stackoverflow.com/questions/7576247/scripting-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!