• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 244
  • Last Modified:

script help for inserting a middle line

Hi,

I have a script problem which I have been struggling with. I want to amend a previously script with the main purpose of inserting a line of text in the middle of a given file, instead of the firstline.

The shell script that I want to amend is as follow:

echo "Enter new line of text:"

read line

echo "Enter file name:"

read file

if test -f $file
then
       echo $line > temp.$$
       cat $file >> temp.$$
       mv temp.$$ $file
else
       echo $file does not exists  or is not a file
fi

Can you help me??
0
FirstMan
Asked:
FirstMan
1 Solution
 
ghostdog74Commented:
you can try this awk script

awk '{
   s[++c]=$0
}
END{
   for(i=1;i<=c;i++){
        if (i==int(c/2)+1) {
           print "my line inserted"
             print i, s[i]
        }
        else {
             print s[i]
        }
   }
}' "file"
0
 
omarfaridCommented:
Hi,

Try this:

echo "Enter new line of text:"

read line

echo "Enter file name:"

read file

if test -f $file
then
       len=`wc -l < $file`
       if test $len -gt 0
       then
              mid=`expr $len / 2`
              rem=`expr $len - $mid`
              head -$mid $file > temp.$$
              echo $line >> temp.$$
              tail -$rem $file >> temp.$$
              mv temp.$$ $file
       else
             echo $line > $file
       fi
else
       echo $file does not exists  or is not a file
fi
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now