jiadong
jiadong

Reputation: 316

How to delete the "0"-row for multiple fles in a folder?

Each file's name starts with "input". One example of the files look like:

0.0005
lii_bk_new
traj_new.xyz   
0
73001
146300 

I want to delete the lines which only includes '0' and the expected output is:

0.0005
lii_bk_new
traj_new.xyz   
73001
146300

I have tried with

sed -i 's/^0\n//g' input_*

and

grep -RiIl '^0\n' input_* | xargs sed -i 's/^0\n//g'

but neither works.
Please give some suggestions.

Upvotes: 2

Views: 69

Answers (3)

Daweo
Daweo

Reputation: 36380

Please give some suggestions.

I would use GNU awk -i inplace for that following way:

awk -i inplace '!/^0$/' input_*

This simply will preserve all lines which do not match ^0$ i.e. (start of line)0(end of line). If you want to know more about -i inplace I suggest reading this tutorial.

Upvotes: 2

Ed Morton
Ed Morton

Reputation: 203284

$ sed '/^0$/d' file
0.0005
lii_bk_new
traj_new.xyz
73001
146300

In your regexp you were confusing \n (the literal LineFeed character which will not be present in the string sed is analyzing since sed reads one \n-separated line at a time) with $ (the end-of-string regexp metacharacter which represents end-of-line when the string being parsed is a line as is done with sed by default).

The other mistake in your script was replacing 0 with null in the matching line instead of just deleting the matching line.

Upvotes: 2

RavinderSingh13
RavinderSingh13

Reputation: 133458

Could you please try changing your attempted code to following, run it on a single Input_file once.

sed 's/^0$//' Input_file

OR as per OP's comment to delete null lines:

sed 's/^0$//;/^$/d' Input_file

I have intentionally not put -i option here first test this in a single file of output looks good then only run with -i option on multiple files.

Also problem in your attempt was, you are putting \n in regex of sed which is default separator of line, we need to put $ in it to tell sed delete those lines which starts and ends with 0.

In case you want to take backup of files(considering that you have enough space available in your file system) you could use -i.bak option of sed too which will take backup of each file before editing(this isn't necessary but for safer side you have this option too).

Upvotes: 2

Related Questions