Operating System - HP-UX
1837240 Members
5494 Online
110115 Solutions
New Discussion

edit a file in non interaction mode in shell scripts

 
jane zhang
Regular Advisor

edit a file in non interaction mode in shell scripts

hi,
I need to delete some lines with certain pattern ( eg. $ABC, and $ABC value varies each time in the loop) in a file and then save the changed file.
how can it do this with vi or ed? I do not want to use sed because sed can not change the original, redirection is not preferable in my case.

Please give me a example.

Thanks for the help.


2 REPLIES 2
A. Clay Stephenson
Acclaimed Contributor

Re: edit a file in non interaction mode in shell scripts

Well if you insist on doing this without making temp files, here you go:

perl -i.safe -n -e 'if (!(m/ABC/)) { print $_;}' file1 file2 myfile*

That will delete all lines with 'ABC' in them
in files file1, file2, and myfile* AND it will create backup copies file1.safe file2.safe ...

If you just use the -i without a suffix, no backup will be created.

If your search pattern changes; you could write a shell script to build your perl script 'on the fly' and then invoke.

I warn you that running this with the -i.safe is dangerous because you are doing it in place so test throughly before using this.

man perlrun to get an idea of what this is doing. The -n argument loops over ever line of input.
If it ain't broke, I can fix that.
jane zhang
Regular Advisor

Re: edit a file in non interaction mode in shell scripts

Hi all,
I figured out the answer,
#!/usr/bin/ksh
EPI_ID=ABC
ed abc.txt <1,$ g/$EPI_ID/d
.
w
q
EOF

Thanks,
Jane