bash - 验证文件中的字段数据并替换为整数
问题描述
我在文件中有以下数据。正如您在某些行中看到的第 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
解决方案
假设:
- 数据不包含分隔符 (
=
) - 所有记录都有 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
推荐阅读
- tensorflow - keras.utils.Sequence 与多个文件
- python - 如何正确读取 csv 文件并返回数据以用于其他功能
- python - 尝试用树枝为不断增长和收缩的细丝设置动画
- qt - 如何在windows上制作qmake生成的Makefile?(nmake 和 mingw-make)
- python - 在字符串中查找连续的字母
- javascript - 以数组作为输入参数实现斐波那契
- ios - 在主线程上重新加载表部分时出现 Swift NSInternalInconsistencyException
- react-native - 如何修复“未定义不是对象(评估'this [BASE_OBJECT] [key]')”
- android - 如何在 XML 中设置 TextView 的 Drawable 的颜色 - 适用于 Android API 15?
- python - Should I use multi-rows or multi-columns with Pandas DataFrame?