首页 > 解决方案 > 验证文件中的字段数据并替换为整数

问题描述

我在文件中有以下数据。正如您在某些行中看到的第 5 字段具有一些整数,例如 100、300 等,并且某些行第 5 字段包含字符串值作为“值”。我希望任何行中的第 5 个字段不包含要替换为“= 100”的整数。

domain=server=hgdndh=0=100=value
domain=server=mds-hnfgd=0=200=value
domain=server=fjghgn=0=value
domain=server=skrufh=0=value
domain=server=kfhgnvb=0=value
domain=server=jghfnf=0=value
domain=server=fhf-ejeu-fkgj=0=100=value
domain=server=fhdnd=0=300=value

以下是我正在寻找的输出:

domain=server=hgdndh=0=100=value
domain=server=mds-hnfgd=0=200=value
domain=server=fjghgn=0=100=value
domain=server=skrufh=0=100=value
domain=server=kfhgnvb=0=100=value
domain=server=jghfnf=0=100=value
domain=server=fhf-ejeu-fkgj=0=100=value
domain=server=fhdnd=0=300=value

使用下面的代码,我得到了文件在第 5 个字段具有字符串的那些详细信息行,但是请您帮我替换该字符串并获得上述输出。

while read -r line
do
line_a=$(echo $line|awk -F"=" '{print $5}')
re='^[0-9]+$'
if ! [[ $line_a =~ $re ]] ; then
echo "Not a string"
fi
done < file.txt

标签: bashshell

解决方案


假设:

  • 数据不包含分隔符 ( =)
  • 所有记录都有 5 或 6 个=分隔的字段
  • 对于有 5 个字段的记录,我们希望保留最后一个/第 5 个字段(例如,value在样本数据中)
  • 对于有 5 个字段的记录,我们希望100在当前的第 4 个和第 5 个字段之间插入一个新字段(例如,在示例数据中)

一个awk想法:

$ awk -F'=' 'BEGIN {OFS=FS} NF==5 {$6=$5;$5=100} 1' file.txt
domain=server=hgdndh=0=100=value
domain=server=mds-hnfgd=0=200=value
domain=server=fjghgn=0=100=value
domain=server=skrufh=0=100=value
domain=server=kfhgnvb=0=100=value
domain=server=jghfnf=0=100=value
domain=server=fhf-ejeu-fkgj=0=100=value
domain=server=fhdnd=0=300=value

100用变量引用替换硬编码:

$ newvalue=100
$ awk -v newv="${newvalue}" -F'=' 'BEGIN {OFS=FS} NF==5 {$6=$5;$5=newv} 1' file.txt
domain=server=hgdndh=0=100=value
domain=server=mds-hnfgd=0=200=value
domain=server=fjghgn=0=100=value
domain=server=skrufh=0=100=value
domain=server=kfhgnvb=0=100=value
domain=server=jghfnf=0=100=value
domain=server=fhf-ejeu-fkgj=0=100=value
domain=server=fhdnd=0=300=value

推荐阅读