Home > Back-end >  add ### at the beginning of a file if there is a match with the content of a list of strings in anot
add ### at the beginning of a file if there is a match with the content of a list of strings in anot

Time:09-27

I have a file with some strings, I need to grep these strings in another file and if match add ### at the beginnig of the line that match.

Assuming this file (1.txt) the file with strings:

123  
456  
789  

and this one the file (2.txt) where to perform the add of the ###:

mko 123 nhy  
zaq rte vfr  
cde nbv 456  
789 bbb aaa  
ooo www qqq  

I'm expecting this output:

###mko 123 nhy  
zaq rte vfr  
###cde nbv 456  
###789 bbb aaa  
ooo www qqq  

I've already tried the following without success:

cat 1.txt |while read line ; do sed '/^$line/s/./###&/' 2.txt >2.txt.out; done

CodePudding user response:

With your shown samples please try following awk code.

awk '
FNR==NR{
  arr[$0]
  next
}
{
  for(i=1;i<=NF;i  ){
    if($i in arr){
       $0="###" $0
       break
    }
  }
}
1
'  1.txt 2.txt

Explanation: Adding detailed explanation here.

awk '                  ##Starting awk program from here.
FNR==NR{               ##Checking condition when 1.txt is being read.
  arr[$0]              ##Creating array arr with index of current line.
  next                 ##next will skip all further all statements from here.
}
{
  for(i=1;i<=NF;i  ){  ##Traversing through all fields from here.
    if($i in arr){     ##Checking if current field is present in arr then do following.
       $0="###" $0     ##Adding ### before current line.
       break;
    }
  }
}
1                      ##Printing current edited/non-edited line here.
'  1.txt 2.txt         ##Mentioning Input_file names here.

CodePudding user response:

This might work for you (GNU sed):

sed 's@.*@/&/s/^#*/###/@' file1 | sed -f - file2

Create a sed script from file1 and run it against file2.

CodePudding user response:

$ while read -r line; do sed -i "/\<$line\>/s/^/###/" 2.txt; done < 1.txt
$ cat 1.txt
###mko 123 nhy  
zaq rte vfr  
###cde nbv 456  
###789 bbb aaa  
ooo www qqq
  • Related