Home > database >  replace string with exact match in bash script
replace string with exact match in bash script

Time:12-24

I have a many repeated content as give below in a file . These are only uniq content.

CHECKSUM="Y" 
CHECKSUM="N" 
CHECKSUM="U" 
CHECKSUM="

I want to replace empty field with "Null" and need output as :

CHECKSUM="Y"
CHECKSUM="N"
CHECKSUM="U"
CHECKSUM="Null"

What I can think of as :

#First find the matching content
cat file.txt | egrep 'CHECKSUM="Y"|CHECKSUM="N"|CHECKSUM="U"' > file_contain.txt
# Find the content where given string are not there    
cat file.txt | egrep -v 'CHECKSUM="Y"|CHECKSUM="N"|CHECKSUM="U"' > file_donot_contain.txt
# Replace the string in content not found file
sed -i 's/CHECKSUM="/CHECKSUM="Null"/g' file_donot_contain.txt 
# Merge the files    
cat file_contain.txt file_donot_contain.txt > output.txt

But I find this is not efficient way of doing. Any other suggestion ?

CodePudding user response:

To achieve this you need to mark that this is the end of the line, not just part of it, using $ (And optionally ^ to mark the start of the line too):

sed -i s'/^CHECKSUM="$/CHECKSUM="Null"/' file.txt
  • Related