in unix system, replace string in file, with variouse position
I work on uni开发者_Go百科x server.
I have many csv files containing, among other info, date fields.I have to replace some of this date fields with another value, for example 20110915 to 20110815. Their position is variable from a file to another.
The problem is that the substitution is position field specific. For example, if my file has row like this:
blablabla;12;0.2121;20110915;20110915;19951231;popopo;other text;321;20101010
I have to replace only first date fields and not other, transforming row in:
blablabla;12;0.2121;20110815;20110915;19951231;popopo;other text;321;20101010
Is there a way to restrict the replace in file, using some constraints?
Thanks
You can try awk
:
awk 'BEGIN {FS=";";OFS=";"} {if($4=="20110915")$4="20110815"; print}' input.csv
How it works:
FS
and OFS
define the input and output field separators. It compares the fourth field ($4) against 20110915
. If it matches, it is changed to 20110815
. The line is then printed.
Here is an alternative using gsub in awk:
awk 'BEGIN {FS=";";OFS=";"} {gsub(/20110915/,20110815,$4); print}' input.csv
Here is a method, if you have to substitute in a range of fields/columns (e.g. 4-4):
awk 'BEGIN {FS=";";OFS=";"} {for(i=4;i<=4;i++){gsub(/20110915/,20110815,$i)}; print}' input.csv
精彩评论