Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Requirement : ADD someting (i.e #) in begining of every line in file A which is grep from file B

File A


File B


grep file B from file A and add "#" character in begining of the file in file A

out put shoude be

share|improve this question

One way:

awk 'NR==FNR{a[$0];next}$0 in a{printf "#";}1'  fileB fileA


NR==FNR{a[$0];next} => awk reads the fileB into an array.

$0 in a{printf "#";} => If any line of fileA matches with any of the array content, put a # in the beginning.

1 => Print every line of fileA

Using sed:

$ x=$(sed -e :a -e 'N;s/\n/\\|/;ta' FileB)
$ sed "s/$x/#&/" FileA

The 1st sed command prepares a string where all lines are joined together as a string and are delimited by a "|" and stored in $x. The 2nd sed inserts a # in the beginning for a line matching with any of the patterns stored in variable $x.

share|improve this answer
Thaks Very much ... i am trying to find out with "SED"..... – Daya Apr 8 '13 at 10:07
added the sed solution.. – Guru Apr 8 '13 at 10:17
Thank again ..... could you pls. explain the awk logic ... – Daya Apr 8 '13 at 10:52

I was able to do this with the following oneliner:

sed "$(for str in $(cat fileB); do echo -n "s/$str/#\0/; "; done;)" fileA

The sed command is constructed in a subshell by looping over the fileB. This then used to replace the matching lines with a # and the matched line.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.