如果里面的awk语句更改值 [英] If statement inside awk to change a value
问题描述
我有以下文件
...
模式Pê
IMP:P 1 0 19R
IMP:电子1 19R 0
...
SDEF POS = 0 0 14.6 AXS = 0 0 1 EXT = D3 RAD = D4单元= 23 = ERG D1 PAR = 2
SI1大号0.020
SP1 1
SI4 0 3.401
SI3 0.9
...
NPS 20000000
我想做以下任务
- 检查后序
= ERG
有一个数字或一个字符串。 - 如果它是一个字符串,找到序列
SI1→
和更改后的值,使用值用户的输入。 - 如果它是一个数字,使用值用户的输入更改数字。
请注意,如果在 ERG =
有一个数字,就没有 SI1→
序列。
有关实例编号2可以通过完成以下
#! /斌/庆典瓦尔斯=(0.02 0.03 0.04 0.05)为VAL在$ {丘壑[@]};做
AWK -vval =$ val的'$ 1 ==SI1{$ 3 = VAL} 1'20
DONE
如何用上述的算法可以实现吗?
#!/斌/庆典VAL =$ @AWK -v VAL =$ val的
BEGIN {I = 1;拆分(VAL,V,)}
#如果它是一个字符串,找到序列SI1 L和修改后的值,使用值用户输入
/ SDEF POS * ERG = [A-ZA-Z] + / {标志=Y。 }
/ SI1 L / {如果(标志==Y){$ 3 = v [I]我++;标志为N的; }}
#如果它是一个数,改变使用的值,该用户输入的数目。
/ SDEF POS * ERG = [0-9] + / {子(/ ERG = [0-9] * /,ERG =V [I],$ 0); i ++在; }
1
'文件
提示:
如果规则发现ERG至少有一个或多个字母([A-ZA-Z] +,将设置标志。
在/ SI1 L /规则将只触发,如果设置了标志。如果规则触发后,将再次取消设置标志,这样任何下列/ SI L /不会再次触发。
。*代表0-N标志或字符
[A-ZA-Z] +代表1-N字母字符大写或小写
I have the following file
...
MODE P E
IMP:P 1 19r 0
IMP:E 1 19r 0
...
SDEF POS= 0 0 14.6 AXS= 0 0 1 EXT=d3 RAD= d4 cell=23 ERG=d1 PAR=2
SI1 L 0.020
SP1 1
SI4 0. 3.401
SI3 0.9
...
NPS 20000000
I want to do the following task
- Check if after the sequence
ERG=
there is a number or a string. - If it's a string, find the sequence
SI1 L
and change the value after that, using values that the user inputs. - If it's a number, change the number using values that the user inputs.
Note that if after ERG=
there is a number, there will be no SI1 L
sequence.
For instance number 2 can be accomplished using the following
#! /bin/bash
vals=(0.02 0.03 0.04 0.05)
for val in "${vals[@]}"; do
awk -vval="$val" '$1=="SI1"{$3=val}1' 20
done
How can the above algorithm be achieved?
#!/bin/bash
val="$@"
awk -v val="$val" '
BEGIN { i=1; split (val,v," ") }
# If it is a string, find the sequence SI1 L and change the value after that, using values that the user inputs
/SDEF POS.*ERG=[a-zA-Z]+/ { flag="y" ; }
/SI1 L/ { if (flag=="y") { $3=v[i]; i++; flag="n"; } }
# If it is a number, change the number using values that the user inputs.
/SDEF POS.*ERG=[0-9]+ / { sub(/ERG=[0-9]*/, "ERG="v[i],$0);i++; }
1
' file
hints:
If the rule find ERG with at least one or more letters ([a-zA-Z]+, it will set the flag. The /SI1 L/ rule will only triggers, if the flag is set. If the rule triggered, it would unset the flag again, so that any following /SI L/ wouldn't trigger again.
.* stands for 0-n sign or character
[A-Za-z]+ stands for 1-n alphabetic character in lower or upper case
这篇关于如果里面的awk语句更改值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!