在bash中修改.txt文件中的行 [英] modify line in a .txt file in bash

查看:113
本文介绍了在bash中修改.txt文件中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.txt,其中包含行,这些行又依次用,"分隔,例如:

I have a .txt that contains lines and these in turn data separated by "," for example:

10,05,nov,2016,122,2,2,330,user

我想要的是能够修改X线的参数,该方法的搜索方法是第一个数字,该数字是唯一的,因此不会重复. 例如,找到数字10(f1)并修改包含122(f5)的行. 我已经用sed尝试过了,但是我做不到. 我认为使用awk可以,但是我没有研究该命令. 有帮助吗?

What I want is to be able to modify a parameter of an X line, which the search method is the first number, which is unique, is not repeated. For example find the number 10 (f1) and modify the row containing the 122 (f5). I've tried it with sed but I can't do it. I've commented that with awk I could, but I did'nt study that command. Some help??

推荐答案

像下面这样的简单awk脚本应该可以解决问题:

A simple awk script like the following should do the trick :

awk -v find="10" -v field="5" -v newval="abcd" 'BEGIN {FS=OFS=","} {if ($1 == find) $field=newval; print $0}' test.csv

说明:

  • awk -v find="10" -v field="5" -v newval="abcd":为awk定义3个变量. find,其中包含我们要查找的模式; field,其中包含我们要编辑的字段的编号; newval,其中包含要替换的值.
  • BEGIN {FS=OFS=","}:在遍历文件之前,我们将文件分隔符和输出文件分隔符设置为,".
  • if ($1 == find) $field=newval:如果一行的第一个字段包含所需的模式,则将第N个字段(如果$field=1则为第一个,如果$field=2则为第二个,...)设置为newval
  • print $0:无论if测试的结果如何,我们都会打印整行.
  • awk -v find="10" -v field="5" -v newval="abcd" : defines 3 variables for awk. find, that contains the pattern we are looking for,field that contains the number of the field we want to edit, and newval with the value to replace.
  • BEGIN {FS=OFS=","} : before iterating through the file, we set the File Separator and Output File Separator to ",".
  • if ($1 == find) $field=newval: if the 1rst field of a line contains the pattern we want, we set the Nth field (1st if $field=1, 2nd if $field=2, ...) to the value of newval
  • print $0: whatever the result from the if test, we print the whole line.

此脚本的较短版本(但较难理解)可以写成:

A shorter (but less understandable) version of this script could be written as follow :

awk -v a="10" -v f="5" -v n="abcd" -F, '$1 == a {$f=n}OFS=FS' test.csv

其中a表示findf表示fieldn表示newval-F,表示FS=","

Where a refers to find, f refers to field, n refers to newval and -F, refers to FS=","

运行中的脚本:

> cat test.csv
11,05,nov,2016,122,2,2,330,user
10,05,nov,2016,123,2,2,330,user
12,05,nov,2016,124,2,2,330,user

> awk -v find="10" -v field="5" -v newval="abcd" 'BEGIN {FS=OFS=","} {if ($1 == find) $field=newval; print $0}' test.csv
11,05,nov,2016,122,2,2,330,user
10,05,nov,2016,abcd,2,2,330,user
12,05,nov,2016,124,2,2,330,user

这篇关于在bash中修改.txt文件中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆