Hi,

I wish to delete the last three lines of a file iteratively. I tried this in unix shell scripting but it is not working..

lines=$(wc -l < s27.cnf)
target=$((lines-2))
sed '$target,$lines d' s27.cnf > f2.cnf
mv f2.cnf s27.cnf

I am getting an error "sed: 1: "$target,$lines d": undefined label 'arget,$lines d'
So was not sure what to use.

I would appreciate help on this.

Dani AI

Generated

The error came from quoting: single quotes prevent the shell from expanding $ variables, so sed received a literal string and failed. correctly pointed that out. 's sed-only one-liner is a good streaming solution (no temp file) and is the most efficient for very large inputs, but there are several simpler, portable alternatives depending on your environment.

A compact approach (works on GNU and modern BSD coreutils) is to ask the tool that prints the first N- lines to write a temporary file and then replace the original:

head -n -3 s27.cnf > f2.cnf && mv f2.cnf s27.cnf

If you need a POSIX-portable method (more shells, older Unixes), use awk to keep lines and print everything except the final N. This is easy to read and adjust:

awk -v n=3 '{ a[NR] = $0 } END { for (i = 1; i <= NR - n; i++) print a[i] }' s27.cnf > f2.cnf

Practical notes and troubleshooting

  • If you choose the temp-file route, create the temp file safely (use mktemp) and mv it back; mv is atomic only on the same filesystem and may change permissions/ownership if done across filesystems.
  • Guard against files shorter than N lines (do nothing if total lines <= N).
  • If you prefer in-place edits, use the platform-specific in-place flag for sed (behaves differently on GNU vs BSD), or use streaming solutions like ’s sed one-liner to avoid temp files.
  • For iterative deletion in a loop, recompute the file length each iteration and stop when the file is too short.

These options let you pick the simplest method for your platform and file size while avoiding the quoting pitfall that caused the original error.

Recommended Answers

All 4 Replies

Single quotes disable substitution, so perhaps

sed "$target,$lines d" s27.cnf > f2.cnf
sed $target','$lines' d' s27.cnf > f2.cnf

Hey there,

You can also do it this way

sed -e :a -e '$d;N;2,3ba' -e 'P;D' s27.cnf >f2.cnf

Just change the 3 to hower many lines you want to delete from the bottom

Best wishes,

Mike

Thanks...it worked...

I appreciate the help

Your welcome, of course :)

Best wishes,

Mike

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.