Reputation: 1
Good day!
Using bash, how can I replace the record in the fourth field by 9010 if the condition below is meet:
NOTE: Fixed width
60000123456789100002130G7 2.01408190151529E+28 1E+31 1000
60000023456789100002130G7 2.01408190151529E+28 1E+31 1050
Upvotes: 0
Views: 91
Reputation: 203712
$ awk '!(substr($0,2,5)+0){sub($NF"$",9010)} 1' file
60000123456789100002130G7 2.01408190151529E+28 1E+31 1000
60000023456789100002130G7 2.01408190151529E+28 1E+31 9010
Upvotes: 1
Reputation: 3125
Avinash Raj and Perreal, why do you assume that the five zeros are consecutive?
Avinash Raj, why do you ignore the first and the seventh digits?
awk '{ S=substr($0,1,7); gsub("[^0]","",S); if (length(S)==5) $4=9010; print }'
To keep the formating spaces:
1) assuming three spaces from one field to the next one:
awk '{ S=substr($0,1,7); gsub("[^0]","",S); if (length(S)==5) $4=9010; print $1" "$2" "$3" "$4}'
2) Assuming a non-negative integer number ([0-9]+) at the end of the input line:
awk '{ S=substr($0,1,7); gsub("[^0]","",S); L=$0; if (length(S)==5) sub("[0-9]+$","9010",L); print L}'
3) Assuming there are only four fields in the input line.
awk '{ S=substr($0,1,7); gsub("[^0]","",S); L=$0; if (length(S)==5) sub($4"$","9010",L); print L}'
4) To retain the original full-length space separators:
awk '
{
S=substr($0,1,7)
gsub("[^0]","",S)
if (length(S)!=5) {
print
next
}
$4=9010
N=split($0,GAP,"[^ ]+")
L=""
for(i=1;i<=N;i++) L = L GAP[i] $i
print L
}'
Upvotes: 0
Reputation: 97968
Using awk
, assuming you meant exactly 5 consecutive 0's:
awk '/^[1-9]{,2}0{5}[^0]/{$4=9010}1' input
Using GNU sed
without any assumptions:
sed 'h;s/^\(.......\).*/\1/;s/0//g;/^..$/{x;s/[^ ]*$/9010/;b};x' input
Gives:
60000123456789100002130G7 2.01408190151529E+28 1E+31 1000
60000023456789100002130G7 2.01408190151529E+28 1E+31 9010
Upvotes: 1
Reputation: 785316
This awk should work:
awk '{s=substr($0, 1, 7); gsub(/0+/, "", s)} length(s)<=2{$4="9010"} 1' file
60000123456789100002130G7 2.01408190151529E+28 1E+31 1000
60000023456789100002130G7 2.01408190151529E+28 1E+31 9010
To get the formatting right pipe with column -t
:
awk '{s=substr($0, 1, 7); gsub(/0+/, "", s)} length(s)<=2{$4="9010"} 1' file | column -t
60000123456789100002130G7 2.01408190151529E+28 1E+31 1000
60000023456789100002130G7 2.01408190151529E+28 1E+31 9010
EDIT: To get formatting right without using column -t
:
awk -v OFS='\t' '{s=substr($0, 1, 7); gsub(/0+/, "", s)} length(s)<=2{$4="9010"}
{for (i=1; i<=NF; i++) printf "%s%s", $i, (i<NF)?OFS:RS}' file
60000123456789100002130G7 2.01408190151529E+28 1E+31 1000
60000023456789100002130G7 2.01408190151529E+28 1E+31 9010
Upvotes: 0
Reputation: 174736
Through awk,
awk '/^.00000.*/{sub(/^.*$/,"9010",$4);}1' file
Upvotes: 0