Operating System - HP-UX
1834772 Members
3177 Online
110070 Solutions
New Discussion

How to find a particular line and add a new line

 
SOLVED
Go to solution
Purusa
Frequent Advisor

How to find a particular line and add a new line

Hi all,

I want to have a solution for this scenario.
I have a file which has an entry #Pankaj only in one line. I have to make a new file whereby this entry should be preserved and next line should be " I am here ". To summarize I have a file f1 which has contents:
abc asdfnas
efg ooeooeo
#Pankaj
dkkd kdkfdjfj dkfdjd
kdkf dfdslf

I have to transform this file to f2 which has contents:
abc asdfnas
efg ooeooeo
#Pankaj
I am here ( new line to be added)
dkkd kdkfdjfj dkfdjd
kdkf dfdslf

Can someone suggest me a easy way out???

Regds,
Pankaj
A deep chasm can't be crossed in two steps
6 REPLIES 6
curt larson_1
Honored Contributor
Solution

Re: How to find a particular line and add a new line

awk '/^#Pankaj/ {
print $0; print "I am here";next;}
{print;}' < f1 > f2
Sridhar Bhaskarla
Honored Contributor

Re: How to find a particular line and add a new line

Pankaj,

You can use 'sed' also though I personally would use awk solution given above.

sed -e '/#Pankaj/{G;s/$/I am here/;}' text

-Sri
You may be disappointed if you fail, but you are doomed if you don't try
shan_7
Advisor

Re: How to find a particular line and add a new line

hi,

you can do thru this vi editor
#vi f1
abc asdfnas
efg ooeooeo
#Pankaj
dkkd kdkfdjfj dkfdjd
kdkf dfdslf
then edit whatever u want then while saving
in command mode of vi
:w filename(f2)

i think this will do for you

Shankar

Mel Burslan
Honored Contributor

Re: How to find a particular line and add a new line

longer but shell only way of doing this (without perl knowledge)

#!/usr/bin/ksh

if [ -a /tmp/newfile.000]
then
rm /tmp/newfile.000
fi

cat filename | while read line
do
grep -q Pankaj $line
r=`echo $?`
echo $line >> /tmp/newfile.000
if [ $r -eq 0 ]
then
echo "I am here" >> /tmp/newfile.000
fi
done

this will place the line right after every line that contains the word "Pankaj".

Hope this helps.


line=`grep -n Pankaj filename|cut -d: -f1`
total_lines_in_file=`cat filename | wc -l`
________________________________
UNIX because I majored in cryptology...
Purusa
Frequent Advisor

Re: How to find a particular line and add a new line

Hi,

THanx for all the wonderful solutions.

Curt, it would be great if you could explain me the working of solution given by you as thats the one I am planning to implement.

Regds,
Pankaj
A deep chasm can't be crossed in two steps
Manish Srivastava
Trusted Contributor

Re: How to find a particular line and add a new line

Hi,

It says that if the line is begining with #Pankaj, print it (print $0) to the output and then print "I am here" and goto next line of the output.

It ithe line does not begin with #Pankaj then just print the line. (The last line)

f2 is put the output to f2.

HTH
manish.

(please assign points to Curt and others)