i have to replace all the ? with X in unix except some valid?

Viewed 79

It kind of some complicated question. I want to replace all the ? in the file with X. But the problem is there are some valid ? also there in input file.

eg:

input:

HELLO ?, WELCOME TO THE NEW WORLD??23, and you are most ? valid person.

output:

HELLO X, WELCOME TO THE NEW WORLDX?23, and you are most X valid person.

here, ? comes before 23 is valid one.. like ?23, many values are there. ?24,?33,?45, etc.,

I tried with sed script, but able to find the exact command.

Script which i used:

LINE_NUM=0 

while IFS= read -r LINE    
do  
LINE_NUM=$?   
EXTRACTED=`echo "${LINE}" |grep '?23' |  sed 's|^.*\?23||; s|\?[0-9].*$||'`

if [ -n "$EXTRACTED" ]    
then    
UPDATED=`echo "$EXTRACTED" | sed 's/?/X/g'`    
UPDATED_1=`echo "$UPDATED" | awk '{gsub("/","%",$0); print}'`    
if [ $EXTRACTED != $UPDATED ]   
then    
LATEST_VALUE=`echo  "${LINE}" | sed "s|${EXTRACTED}|${UPDATED}|g"`    
fi

LATEST_VALUE=`echo  "${LINE}"`    
echo "$LATEST_VALUE"  >> outputfile.txt   
else    
echo "$LINE" >> outputfile.txt    
fi   
done<inputfile.txt
2 Answers
$ echo "HELLO ?, WELCOME TO THE NEW WORLD??23, and you are most ? valid person." | 
  sed -E 's/\?([^0-9]|$)/X\1/g'


HELLO X, WELCOME TO THE NEW WORLDX?23, and you are most X valid person.

here it escapes ? followed by a digit (or end of line). If your list is more restricted change the regex there.

With your shown samples, please try following. In GNU awk please try following. Simple explanation would be, setting record separator as 1 ? followed by 1 digit, using global substitution to substitute ? with X in current records; setting correct output record separator as RT, then print current line.

awk -v RS='[?][0-9]' '{gsub(/\?/,"X");ORS=RT} 1' Input_file
Related