如何更改.dat文件中特定列的值巴什

时间:2016-03-27 19:39:31

标签: bash shell unix awk sed

我有这个.dat文件

#id|firstName|lastName|gender|birthday|creationDate|locationIP|browserUsed
933|Mahinda|Perera|male|1989-12-03|2010-03-17T13:32:10.447+0000|192.248.2.123|Firefox
1129|Carmen|Lepland|female|1984-02-18|2010-02-28T04:39:58.781+0000|81.25.252.111|Internet Explorer
4194|Hồ Chí|Do|male|1988-10-14|2010-03-17T22:46:17.657+0000|103.10.89.118|Internet Explorer
8333|Chen|Wang|female|1980-02-02|2010-03-15T10:21:43.365+0000|1.4.16.148|Internet Explorer

我希望输入idcolumnvalue来将特定column的当前值更改为新value并指定id为输入提供的列。

示例,对于命令

myscript.sh -f datfile.dat --edit 933 3 patrikopoulos

我希望我的文件成为

#id|firstName|lastName|gender|birthday|creationDate|locationIP|browserUsed
933|Mahinda|patrikopoulos|male|1989-12-03|2010-03-17T13:32:10.447+0000|192.248.2.123|Firefox
1129|Carmen|Lepland|female|1984-02-18|2010-02-28T04:39:58.781+0000|81.25.252.111|Internet Explorer
4194|Hồ Chí|Do|male|1988-10-14|2010-03-17T22:46:17.657+0000|103.10.89.118|Internet Explorer
8333|Chen|Wang|female|1980-02-02|2010-03-15T10:21:43.365+0000|1.4.16.148|Internet Explorer

我在这里堆叠:

if [ "$1" == "-f" ] && [ "$3" == "--edit" ]
then
id="$4"
column="$5"
value="$6"
fi

任何想法?

2 个答案:

答案 0 :(得分:2)

您可以使用awk:

awk -v id=933 -v c=3 -v val='patrikopoulos' 'BEGIN{FS=OFS="|"} $1==id{$c = val} 1' file

<强>输出:

#id|firstName|lastName|gender|birthday|creationDate|locationIP|browserUsed
933|Mahinda|patrikopoulos|male|1989-12-03|2010-03-17T13:32:10.447+0000|192.248.2.123|Firefox
1129|Carmen|Lepland|female|1984-02-18|2010-02-28T04:39:58.781+0000|81.25.252.111|Internet Explorer
4194|Hồ Chí|Do|male|1988-10-14|2010-03-17T22:46:17.657+0000|103.10.89.118|Internet Explorer
8333|Chen|Wang|female|1980-02-02|2010-03-15T10:21:43.365+0000|1.4.16.148|Internet Explorer

答案 1 :(得分:1)

使用sed:

$ id=933; col=3; str="patrikipoulos"
$ sed "/^$id|/s/[^|]*/$str/$col" file
#id|firstName|lastName|gender|birthday|creationDate|locationIP|browserUsed
933|Mahinda|patrikipoulos|male|1989-12-03|2010-03-17T13:32:10.447+0000|192.248.2.123|Firefox
1129|Carmen|Lepland|female|1984-02-18|2010-02-28T04:39:58.781+0000|81.25.252.111|Internet Explorer
4194|Hồ Chí|Do|male|1988-10-14|2010-03-17T22:46:17.657+0000|103.10.89.118|Internet Explorer
8333|Chen|Wang|female|1980-02-02|2010-03-15T10:21:43.365+0000|1.4.16.148|Internet Explorer

如果在第一列中找到933,则搜索3出现的非管道字符并替换为patrikopoulos