【问题标题】:replace string with exact match in bash script在bash脚本中用完全匹配替换字符串
【发布时间】:2022-01-24 12:34:11
【问题描述】:

我在文件中有很多重复的内容,如下所示。这些只是独特的内容。

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

我想用“Null”替换空字段并需要输出为:

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

我能想到的:

#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

但我发现这不是有效的做法。还有什么建议吗?

【问题讨论】:

  • 如果sed 's/="$/&Null"/' file.txt 不是您所需要的,那么edit 您的问题可以更好地解释您的要求并提供更具代表性的示例。

标签: bash shell


【解决方案1】:

要实现这一点,您需要使用$(也可以选择^ 来标记行首)标记这是行尾,而不仅仅是行尾的一部分:

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

【讨论】:

  • 短一点,利用匹配的模式:s/^CHECKSUM="$/&Null"/'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多