LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Sed using a pattern variable at the start of the line doesn't work (https://www.linuxquestions.org/questions/linux-newbie-8/sed-using-a-pattern-variable-at-the-start-of-the-line-doesnt-work-4175521581/)

zbyesk 10-09-2014 12:10 PM

Sed using a pattern variable at the start of the line doesn't work
 
I'm trying to make an script that replaces lines that starts with a pattern given by the lines of other file.

Example lines of the base file:

Code:

& NAME 1
UH  24  1        26.03              1
& NAME 2
UH  27  1        50.05              1

Example lines of the input file:

Code:

UH  24  1        27.68              1
UH  27  1        37.21              1

I just want the script to replace the values (i.ex: 26.03 for 27.68).


I've made the script below but the sed doesn't work.

Code:

while IFS= read -r line
do
    pattern=${line:0:15}
    sed "s/$pattern.*/$line/" BASE.TXT > OUTPUT.TXT
done < INPUT.TXT


Thanks in advance!

Keith Hedger 10-09-2014 01:46 PM

This should do it
Code:

#!/bin/bash
echo "Base file:"
cat BASE.TXT
cp BASE.TXT BASE.TXT.HOLD
while read
        do
                pattern="${REPLY:0:15}"
                sed -i "s/${pattern}.*/$REPLY/" BASE.TXT.HOLD
        done< <(cat INPUT.TXT)
echo
echo
echo "Converted base file:"
cat BASE.TXT.HOLD
echo

You don't need to set IFS, read without a value assigns to the variable REPLY, INPUT.TXT should end in a new line otherwise the last line won't get read in.

After the conversion has been done you can then copy BASE.TXT.HOLD to BASE.TXT if you need to.


All times are GMT -5. The time now is 10:00 AM.