Reputation: 87
I have to process a file with data organized like this
AAAAA:BB:CCC:EEEE:DDDD
FF:III:JJJ:KK:LLL
MMMM:NN:OOO:PP
etc
Columns can have different length but lines always have the same number of columns.
I want to be able to cut a specific column of a given line and change it to the value I want.
For example I'd apply my command and change the file to
AAAAA:BB:XXXX:EEEE:DDDD
FF:III:JJJ:KK:LLL
MMMM:NN:OOO:PP
I know how to select a specific line with sed and then cut the field but I have no idea on how to replace the field with the value I have.
Thanks
Upvotes: 3
Views: 9208
Reputation: 47267
Here's a way to do it with awk
:
Going with your example, if you wanted to replace the 3rd field of the 1st line:
awk 'BEGIN{FS=OFS=":"} {if (NR==1) {$3 = "XXXX"}; print}' input_file
Input:
AAAAA:BB:CCC:EEEE:DDDD
FF:III:JJJ:KK:LLL
MMMM:NN:OOO:PP
Output:
AAAAA:BB:XXXX:EEEE:DDDD
FF:III:JJJ:KK:LLL
MMMM:NN:OOO:PP
Explanation:
awk
: invoke the awk command'...'
: everything enclosed by single-quotes are instructions to awkBEGIN{FS=OFS=":"}
: Use :
as delimiters for both input and output. FS
stands for Field Separator. OFS
stands for Output Field Separator.if (NR==1) {$3 = "XXXX"};
: If Number of Records (NR
) read so far is 1, then set the 3rd field ($3
) to "XXXX
".print
: print the current lineinput_file
: name of your input file.If instead what you are trying to accomplish is simply replace all occurrences of CCC
with XXXX
in your file, simply do:
sed -i 's/CCC/XXXX/g` input_file
Note that this will also replace partial matches, such as ABCCCDD
-> ABXXXXDD
Upvotes: 6
Reputation: 58371
This might work for you (GNU sed):
sed -r 's/^(([^:]*:?){2})CCC/\1XXXX/' file
or
awk -F: -vOFS=: '$3=="CCC"{$3="XXXX"};1' file
Upvotes: 1