0

I have the file containing lines which are pipe separated like below.

45|abc|NULL|hol|
Gha|ghsk|NULL|gah|

How can I replace 3rd column values (Null) with something like a hyphen(-). The value in third column is not unique. Any help would be appreciated?

  • Do you want to A) replace anything in the 3rd col with -, or B) only replace NULL in 3rd col with - or C) want to replace every NULL in any col with -? Sometimes you say Null and sometimes NULL - should the match be case-insensitive? If the 3rd col can sometimes contain values other than NULL then include those cases in your sample input and ditto for cases where NULL appears in other columns. Remember to add the expected output too - showing sample input is just part of what it takes to ask a good question. See How to Ask. – Ed Morton Feb 5 at 14:31
1
awk -F'|' '{ $3 = ($3 == "NULL" ? "-" : $3) } 1' OFS='|' file
  • Sets the input and output field separators to | to preserve the delimiters in your file
  • Check the third field if it is equal to "NULL" then assigns it the value - if not we retain the value as is.
  • 1 at the end prints your line with or without modified 3rd column depending on if our test was successful or not.
  • ($3=="NULL"?"-":$3) is a ternary operator that checks if the condition $3=="NULL" is true or not. If true ? then we assign - and if false : we keep the field as is.

Tests

$ cat positioned
45|abc|NULL|hol|
Gha|ghsk|NULL|gah


$ awk -F'|' '{ $3 = ($3 == "NULL" ? "-" : $3) } 1' OFS='|' positioned
45|abc|-|hol|
Gha|ghsk|-|gah

$ cat positioned
45|abc|NULL|hol|
Gha|ghsk|NULL|gah
95|xyz|NonNULL|hol|
asdf|ghsk|NonNULL|afs|

$ awk -F'|' '{ $3 = ($3 == "NULL" ? "-" : $3) } 1' OFS='|' positioned
45|abc|-|hol|
Gha|ghsk|-|gah
95|xyz|NonNULL|hol|
asdf|ghsk|NonNULL|afs|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.