简体   繁体   中英

SED Linux command to replace in exactly in a line

I have the following batch

#! /bin/bash
PATTERN1="MACRO"
PATTERN2="HI"
sed -e "s/${PATTERN1}/${PATTERN2}/g" config.conf 

So, the content of the file config.conf is

ABC
   DEF
   ERF MACRO
   ERR
MACRO

So, the output of the command is:

ABC
   DEF
   ERF 
   ERR

but the desired output is

ABC
   DEF
   ERF MACRO
   ERR

In other words, I need to replace the pattern only with the exactly match per line, without spaces or other words in the same line.

add ^ and $ to the pattern you want to do exact match

with your example: you can either do:

 sed -e "s/^${PATTERN1}$/${PATTERN2}/g" ...

or use your original sed line, modify the PATTERN1 :

PATTERN1="^MACRO$"

尝试这个:

awk '$0==p {$0=r}8' p="${PATTERN1}" r="${PATTERN2}" file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM