2

I have several files with same extension .txt in a directory. I want to remove the last line from all .txt files.

What I did is

find . -type f -name '*.txt' -exec sed '$d' {} \;

This prints the desired output from sed to the terminal for every .txt file.

What I want is to modify the respective files.

flappingwings
  • 65
  • 1
  • 7
  • 3
    No, you really don't want to do that. You *might* be able to use `sed -i` (if your sed supports this atrocity), but you *really* don't want to. – William Pursell Oct 31 '19 at 12:33
  • 3
    Create a new directory. Filter the files into new files in the new directory with the changes. Attempting to maniuplate large number of files with `sed -i` will work most of the time. But it will fail and cause data loss at the worst possible moment. – William Pursell Oct 31 '19 at 12:34

3 Answers3

2

Try this:--

sed  -i '$d' *.txt

"$" is used as a line number and means the last line in the file.

"d" is usd to delete the respective line(last line in this case).

"*.txt" is used to select all files whose extension is .txt in the present directory.

Ravi Saroch
  • 934
  • 2
  • 13
  • 28
  • Please describe in your answer, what was the problem, and how will this snippet solve it, to help others understand this answer – FZs Nov 01 '19 at 07:20
  • 1
    @FZs If I am correct user want to delete last line from all file whose extension is .txt in particular directory and this command sufficient to do that. – Ravi Saroch Nov 01 '19 at 09:39
  • 2
    I've meant to explain it in your answer... You can edit it anytime! And I don't know whether you're right, I've seen this post in a review queue – FZs Nov 01 '19 at 10:54
  • Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – CertainPerformance Nov 03 '19 at 05:57
1

You should use -i with sed statement

To modify and do some changes in file we need to specify -i in sed command

your command should be like

find . -type f -name '*.txt' -exec sed -i '$d' {} \;

But please note that it will update all the files with .txt and you wont be able to revert back so please take backup of important files

Strick
  • 1,512
  • 9
  • 15
0

Considering the risk of loosing data while modifying large number of files using sed, this is what I used after creating a new sub-directory:

awk 'NR>1 {print last > "./modified/"FILENAME} {last=$0}' *.txt

This filters all the files with extension .txt into new files with changes to the sub-directory named modified.

Ref: what is the easiest way to remove 1st and last line from file with awk?

flappingwings
  • 65
  • 1
  • 7