Bash – awk print something if column is empty

awkbashsed

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

Best Answer

You can do it using this sed script:

sed -r 's/\| +\|/\|blank\|/g' File
abc|pqr|lmn|123
pqr|xzy|321|azy
lee|cha|blank|325
xyz|blank|abc|123

If you don't want the |:

sed -r 's/\| +\|/\|blank\|/g; s/\|/ /g' File
abc pqr lmn 123
pqr xzy 321 azy
lee cha blank 325
xyz blank abc 123

Else with awk:

awk '{gsub(/\| +\|/,"|blank|")}1' File
abc|pqr|lmn|123
pqr|xzy|321|azy
lee|cha|blank|325
xyz|blank|abc|123
Related Topic