bash / sed : editing of the file

Viewed 55

I use sed to remove all lines starting from "HETATM" from the input file and cat to combine another file with the output recieved from SED

sed -i '/^HETATM/ d' file1.pdb
cat fil2.pdb file1.pdb > file3.pdb

is this way to do it in one line e.g. using only sed?

4 Answers

If you want to consider awk then it can be done in a single command:

awk 'FNR == NR {print; next} !/^HETATM/' file2.pdb file1.pdb > file3.pdb

With cat + grep combination please try following code. Simple explanation would be, using cat command's capability to concatenate file's output when multiple files are passed to it and using grep -v to remove all words starting from HETATM in file1.pdb before sending is as an input to cat command and creating new file named file3.pdb from cat command's output.

cat file2.pdb <(grep -v '^HETATM' file1.pdb) > file3.pdb

I'm not sure what you mean by "remove all lines starting from 'HETATM'", but if you mean that any line that appears in the file after a line that starts with "HETATM" will not be outputted, then your sed expression won't do it - it will just remove all lines starting with the pattern while leaving all following lines that do not start with the pattern.

There are ways to get the effect I believe you wanted, possibly even with sed - but I don't know sed all that well. In perl I'd use the range operator with a guaranteed non-matching end expression (not sure what will be guaranteed for your input, I used "XXX" in this example):

perl -ne 'unless (/^HETATM/../XXX/) { print; }' file1.pdb
mawk '(FNR == NR) < NF' FS='^HETATM' f1 f2
Related