Wolfgang
Wolfgang

Reputation: 575

replace text between specific occurrence of delimiter only if it's blank - bash

Dears,

In the below string "|" is the delimiter in the file. If date between 19th and 20th occurrence is blank than replace it with the current date for all the lines in the file.

227354|SD-PD-100456|P-OD-98767318712|ABC|O|EN|UJ|NM|ABC|ABC;ABC;ABC||98765432||I|A||01/04/2019||||06/04/2020||JU|HINB

sed -i "s/\(\([^|]*|\)\{19\}\)[^|]*/\1$(date '+%d\/%m\/%Y')/g" *

by using this command I am able to replace text between 19th and 20th delimiter, however I don't understand how I can only replace if it's blank.

Upvotes: 1

Views: 75

Answers (2)

Beta
Beta

Reputation: 99134

If you're interested in a blank, then look for a blank:

sed -i "s/\(\([^|]*|\)\{19\}\)|/\1$(date '+%d\/%m\/%Y')|/" filename

Upvotes: 1

anubhava
anubhava

Reputation: 785621

awk is more suitable for this job:

awk -v dt=$(date '+%d/%m/%Y') 'BEGIN{FS=OFS="|"} $20 == ""{$20=dt} 1' file

227354|SD-PD-100456|P-OD-98767318712|ABC|O|EN|UJ|NM|ABC|ABC;ABC;ABC||98765432||I|A||01/04/2019|||09/04/2020|06/04/2020||JU|HINB

Details:

  • -v dt=$(date '+%d/%m/%Y'): Send date as command line argument to awk in variable dt
  • BEGIN{FS=OFS="|"}: Sets | as input and output delimiters
  • $20 == "": If column 20 is empty
  • {$20=dt}: Sets value of $20 to variable dt
  • 1: Default action to print a row

Upvotes: 2

Related Questions