问题
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