prabhu
prabhu

Reputation: 321

awk print something if column is empty

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

Upvotes: 3

Views: 17519

Answers (3)

rici
rici

Reputation: 241691

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.

Upvotes: 8

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

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

Upvotes: 6

anubhava
anubhava

Reputation: 785008

You can use awk like this:

awk 'BEGIN{FS=OFS="|"} {for (i=1; i<=NF; i++) if ($i ~ /^ *$/) $i="blank"} 1' file
abc|pqr|lmn|123
pqr|xzy|321|azy
lee|cha|blank|325
xyz|blank|abc|123

Upvotes: 3

Related Questions