Reputation: 59
I have this .dat file
#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
And i want with an input of an id
, a column
and a value
to change current value of a specific column
to the new value
and specify the column from the id
has given for input.
Example , for command
myscript.sh -f datfile.dat --edit 933 3 patrikopoulos
I want my file to become
#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
I am stack somewhere here :
if [ "$1" == "-f" ] && [ "$3" == "--edit" ]
then
id="$4"
column="$5"
value="$6"
fi
any ideas ?
Upvotes: 2
Views: 1395
Reputation: 15461
With 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
If 933
is found in first column, then search 3
rd occurrence of non-pipe characters and replace with patrikopoulos
.
Upvotes: 1
Reputation: 785631
You can use awk for this:
awk -v id=933 -v c=3 -v val='patrikopoulos' 'BEGIN{FS=OFS="|"} $1==id{$c = val} 1' file
Output:
#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
Upvotes: 2