1757970 Members
2882 Online
108866 Solutions
New Discussion юеВ

Deleting line in a file

 
Pando
Regular Advisor

Deleting line in a file

Dear Gurus,

I have a file that contain a line below:

...
Test,1
Code,
Test,2
...

What i want to do is delete the Code, part
so the the file will look like this:

...
Test,1
Test,2
...

Is there a one line command to do this?

Maximum point to all correct answers!
8 REPLIES 8
Ludovic Derlyn
Esteemed Contributor

Re: Deleting line in a file

hi,

it's possible with editor vi

vi "file"

"dd" for suppress line
or
substitution

s/chaine1/chaine2/[g]
s/code/""/g

In attachment, vi instructions
regards
L-DERLYN
H.Merijn Brand (procura
Honored Contributor

Re: Deleting line in a file

That much depends on what your decision to remove that line is based on.
If it's not context sensative, and you just want all lines that look like "Code," be removed,

# perl -ni.org -e'/^Code,$/ or print' file

or

# mv file file.org
# grep -v '^Code,$' file.org >file

The original file will be backed up as file.org
If the removal however is based on context, you need some more. Then it also depends on how big the file is

If the context is just the line before, it's still rather simple

# perl -ni.org -e'$p eq"Test,1\n"&&/^Code,$/ or print;$p=$_' file

If the file is small (for any value of small, which mainly depends on your available system resources), and you want the removal based on the line before *and* after, there are many solutions

# perl -pi.org -e'BEGIN{$/=undef}s{(\A|\n)(Test,1\n)Code,\n(Test,2\n)}{$1$2$3}g' file

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
Pando
Regular Advisor

Re: Deleting line in a file

Hi Procura,

thanks for the input.
what if i dont want to have a backup copy?
what should be the perl command / syntax?
thanks!
H.Merijn Brand (procura
Honored Contributor

Re: Deleting line in a file

just leave out the .org

# perl -pi -e'....' file

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
Sandman!
Honored Contributor

Re: Deleting line in a file

# ex -s +"/^Code/d|wq" inputfile
Pando
Regular Advisor

Re: Deleting line in a file

Hello Procura,

# perl -pi -e'/^Code,$/ or print' file

but the results was:

Test,1
Test,1
Code,
Test,2
Test,2

It does nor remove the Code, but added another line? I might have understood you.
twang
Honored Contributor

Re: Deleting line in a file

use the sed editor:
# sed '/Code/ d' source_file target_file

Hope it can help
twang
H.Merijn Brand (procura
Honored Contributor

Re: Deleting line in a file

I've made that error here before :(

# perl -ni -e'/^Code,$/ or print' file

it is -ni, not -pi
Mea Culpa

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn