Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

File A

abcd
abdc
sdfg
asdfa
jon
ram

File B

jon
abcd

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

out put shoude be

#abcd
abdc
sdfg
asdfa
#jon
ram
share|improve this question
add comment

2 Answers

One way:

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

Explanation:

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
2  
Thank again ..... could you pls. explain the awk logic ... –  Daya Apr 8 '13 at 10:52
add comment

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
add comment

Your Answer

 
discard

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.