Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk print something if column is empty

Tags:

bash

sed

awk

I am trying out one script in which a file [ file.txt ] has so many columns like

abc|pqr|lmn|123
pqr|xzy|321|azy
lee|cha| |325
xyz| |abc|123

I would like to get the column list in bash script using awk command if column is empty it should print blank else print the column value

I have tried the below possibilities but it is not working

cat file.txt | awk -F "|" {'print $2'} | sed -e 's/^$/blank/' // Using awk and sed
cat file.txt | awk -F "|" '!$2 {print "blank"} '
cat file.txt | awk -F "|" '{if  ($2 =="" ) print "blank" } '

please let me know how can we do that using awk or any other bash tools.

Thanks

like image 298
prabhu Avatar asked Dec 06 '25 16:12

prabhu


1 Answers

I think what you're looking for is

awk -F '|' '{print match($2, /[^ ]/) ? $2 : "blank"}' file.txt

match(str, regex) returns the position in str of the first match of regex, or 0 if there is no match. So in this case, it will return a non-zero value if there is some non-blank character in field 2. Note that in awk, the index of the first character in a string is 1, not 0.

Here, I'm assuming that you're interested only in a single column.

If you wanted to be able to specify the replacement string from a bash variable, the best solution would be to pass the bash variable into the awk program using the -v switch:

awk -F '|' -v blank="$replacement" \
    '{print match($2, /[^ ]/) ? $2 : blank}' file.txt

This mechanism avoids problems with escaping metacharacters.

like image 94
rici Avatar answered Dec 09 '25 05:12

rici



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!