1

I need to sed from all *.txt files from line 6 until the end All the results should be in a new single file with the name of each file preceding the results

Example: Having different txt files the result should be one single that looks like this taking from the 3rd line to the end

file 1
3
4
5
file 2
3
4
5
file 3
3
4
5
  • Please edit your question and show us i) your input files and ii) your desired output. Showing ambiguous output (should the file names be in the output or not?) and no input is not very helpful since we can't help get you from here to there unless we know what here is. – terdon Mar 14 '16 at 13:16
2

With GNU sed:

sed -s '1F;6,$!d' -- *.txt > output

Portably, you could use awk instead:

awk 'FNR == 1 {print FILENAME}; FNR>=6' ./*.txt > output

(note that in both cases, hidden files are excluded).

Empty files won't be referenced, but files that have fewer than 6 lines will. If you don't want to hear about those, you can do:

sed -s '6F;6,$!d' -- *.txt > output
awk 'FNR == 6 {print FILENAME}; FNR>=6' ./*.txt > output

Or if you want to see all files:

for f in *.txt; do
  printf '%s\n' "$f"
  tail -n +6 < "$f"
done > output

With GNU tail, you also do:

$ tail -vn +6 -- *.txt
==> a.txt <==
6
7
8
9
10

==> b.txt <==
6
7
8
9
10
  • Thank you, this is perfect I will be using awk is there an edit to this function to make my file look as follow original file: 'file 1 1 2 3 4 5 Done' file needed 'file 1 3 4 5 file 2 3 4 5 6' while having an empty line in between and while removing the last line which is "done" – Chris Mar 14 '16 at 13:32
  • @Chris, I'd suggest asking a separate question for that. – Stéphane Chazelas Mar 14 '16 at 14:48
-2

My suggestion:

ls *.txt | xargs -I {} bash -c "echo {}; sed -n '6,$ p' {}"

Example:

$ seq 10 > 2.txt              
$ seq 12 > 1.txt
$ ls *.txt | xargs -I {} bash -c "echo {}; sed -n '6,$ p' {}"
1.txt
6
7
8
9
10
11
12
2.txt
6
7
8
9
10
  • Please stop piping ls output to xargs. Learn how to use loops. – don_crissti Mar 14 '16 at 13:14
  • I know there are some limitations in this approach related to complex file names. – Sergei Kurenkov Mar 14 '16 at 13:16
  • 2
    Well then do it right. I'm not the downvoter but I can see why people would downvote this answer - it's really bad practice what you're doing there... – don_crissti Mar 14 '16 at 13:17
  • It also has security implications. You should never embed the {} in code arguments. That's enough of a known bad practice to deserve my downvote. – Stéphane Chazelas Mar 14 '16 at 13:19
  • @Stéphane Chazelas, Thanks for mentioning security – Sergei Kurenkov Mar 14 '16 at 14:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.