Yacob
Yacob

Reputation: 525

grep and replace

I wanted to grep a string at the first occurrence ONLY from a file (file.dat) and replace it by reading from another file (output). I have a file called "output" as an example contains "AAA T 0001"

#!/bin/bash
procdir=`pwd`

cat output | while read lin1 lin2 lin3
do
  srt2=$(echo $lin1 $lin2 $lin3 | awk '{print $1,$2,$3}')
  grep -m 1 $lin1  $procdir/file.dat | xargs -r0 perl -pi -e 's/$lin1/$srt2/g'
done

Basically what I wanted is: When ever a string "AAA" is grep'ed from the file "file.dat" at the first instance, I want to replace the second and third column next to "AAA" by "T 0001" but still keep the first column "AAA" as it is. Th above script basically does not work. Basically "$lin1" and $srt2 variables are not understood inside 's/$lin1/$srt2/g'

Example:

in my file.dat I have a row

AAA D ---- CITY COUNTRY

What I want is :

AAA T 0001 CITY COUNTRY

Any comments are very appreciated.

Upvotes: 2

Views: 466

Answers (3)

perreal
perreal

Reputation: 97948

This will only change the first match in the file:

#!/bin/bash
procdir=`pwd`
while read line; do
    set $line
    sed '0,/'"$1"'/s/\([^ ]* \)\([^ ]* [^ ]*\)/\1'"$2 $3"'/' $procdir/file.dat
done < output

To change all matching lines:

sed '/'"$1"'/s/\([^ ]* \)\([^ ]* [^ ]*\)/\1'"$2 $3"'/' $procdir/file.dat

Upvotes: 0

jaypal singh
jaypal singh

Reputation: 77095

If you have output file like this:

$ cat output
AAA T 0001

Your file.dat file contains information like:

$ cat file.dat
AAA D ---- CITY COUNTRY
BBB C ---- CITY COUNTRY
AAA D ---- CITY COUNTRY

You can try something like this with awk:

$ awk '
NR==FNR { 
    a[$1]=$0
    next
} 
$1 in a {
    printf "%s ", a[$1]
    delete a[$1]
        for (i=4;i<=NF;i++) { 
            printf "%s ", $i 
        }
    print ""
    next
}1' output file.dat
AAA T 0001 CITY COUNTRY
BBB C ---- CITY COUNTRY
AAA D ---- CITY COUNTRY

Upvotes: 1

ikegami
ikegami

Reputation: 385657

Say you place the string for which to search in $s and the string with which to replace in $r, wouldn't the following do?

perl -i -pe'
   BEGIN { ($s,$r)=splice(@ARGV,0,2) }
   $done ||= s/\Q$s/$r/;
' "$s" "$r" file.dat

(Replaces the first instance if present)

Upvotes: 0

Related Questions