Luis Lavaire
Luis Lavaire

Reputation: 701

How to delete an specific line of a file using POSIX shell scripts?

I want do delete, say line number three of the file a. How can I do this with tools like sed or awk in a way that it's compatible with the POSIX specification? I know I could do sed -i '3d' a, but the -i flag is not specified by POSIX for sed.

Of course I could run the same sed command without the -i flag, save to a temporary file and then replace the original file with the new one; but I would prefer a one-liner.

Upvotes: 2

Views: 353

Answers (4)

Mark Setchell
Mark Setchell

Reputation: 207465

I am unsure about POSIX compliance, but can suggest using ed to delete the third line of a file as follows:

echo $'3d\nwq' | ed -s YourFile

or, maybe

printf "3d\nwq\n" | ed -s YourFile

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203522

awk 'NR!=3{a[++nr]=$0} END{for (i=1;i<=nr;i++) print a[i] > FILENAME}' file

Upvotes: 1

kvantour
kvantour

Reputation: 26481

A slightly shorter version then Ravinder his script is :

awk '(FNR!=3)' input_file

An awk program is composed of pairs of the form:

pattern { action }

Either the pattern or the action (including the enclosing brace characters) can be omitted. A missing pattern shall match any record of input, and a missing action shall be equivalent to: { print }.

The pattern in this case states checks If the line-number of the file (FNR) is different from 3. If true, perform the default action ({print $0}).

The deletion of the line would read then :

$ awk '(FNR!=3)' input_file > tmp_file && mv tmp_file input_file

Upvotes: 2

RavinderSingh13
RavinderSingh13

Reputation: 133518

Following may help here.

awk -v line=3 'FNR==line{next} 1' Input_file

Explanation:

-v line=3: Means creating awk variable named line whose value is 3 here as per your post.

FNR==line: Checking condition here if line number(awk's out of the box variable) value is equal to variable line value.

{next}: If condition mentioned above is TRUE then putting next will skip all further statements and nothing will happen on 3rd line of Input_file.

1: awk works on method of condition and action so by mentioning 1 making condition as TRUE and not mentioning any action so by default print of line will happen.

In case you want to save output into same Input_file itself then append > temp_file && mv temp_file Input_file to above code too.


Or with sed in case -i option is not there.

sed '3d' Input_file > temp_file && mv temp_file Input_file

POSIX sed page:

http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html

Upvotes: 2

Related Questions