I have input.txt tab-delimited text file around 30K lines, I would like to check each row (s1..s30K lines) for missing value (i.e blank space) and fill the missing value with zero value.See out.txt
input.txt
id no1 no2 no3 no4 s1 23 34 45 12 s2 4 4 s3 4 8 0
out.txt
id no1 no2 no3 no4 s1 23 34 45 12 s2 0 4 4 0 s3 4 0 8 0
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You could do it like this with awk:
awk 'BEGIN { FS = OFS = "t" } { for(i=1; i<=NF; i++) if($i ~ /^ *$/) $i = 0 }; 1' file
Explanation
Setting FS and OFS to tab ensures the output is correctly delimited. The for-loop looks at every field and sets it to zero if it is empty. The one at the end is a shorthand for { print $0 }.
Method 2
I’d prefer:
sed 's/<TAB> /<TAB>0/g' <input.txt >output.txt
Replace <TAB> with the real TAB character (generally obtained by hitting Ctrl-V, then Tab)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0