0

Considering this file:

1 2 3 4 5 

I can extract the last 3 lines with this sed one-liner:

$ /bin/sed input.txt -e ':a;$q;N;4,$D;ba' 

But I would also like to add some characters (# ) in front of each line, so that the output will be like so:

# 3 # 4 # 5 

How can I modify the one-liner to do that? I mean, without adding another sed invocation (with | /bin/sed -e 's/^/# /').

I would prefer to use sed only for the same reasons of the original question, i.e. I have a system with limited binaries available.

2
  • 1
    Why do you not want to use another sed invocation? I mean any issue with using sed two times? Commented Nov 11, 2021 at 18:41
  • Is tac available? If so, reverse the file, extract the first n lines and modify them, then reverse the result. Commented Nov 11, 2021 at 19:03

1 Answer 1

4

Instead of using sed to print the last n lines use tail:

$ tail -3 input.txt | sed 's/^/# /' # 3 # 4 # 5 

Also you don't need to cat the file, see Useless use of cat.

Using sed only:

sed ':a;${s/^/# /;s/\n/&# /g;q;};N;4,$D;ba' input.txt 
9
  • I would prefer to use sed only, as requested in the question. Commented Nov 11, 2021 at 17:51
  • @virtualdj ok, I'll try that, could you explain why sed only? Commented Nov 11, 2021 at 17:52
  • For the same reasons of the original question (unix.stackexchange.com/q/107387/188792), i.e. I have a system with limited binaries available. Commented Nov 11, 2021 at 17:53
  • Upvoters! The sed solution is from @Quasímodo, they added it instead of posting their own answer. Many thanks to they. Commented Nov 11, 2021 at 21:13
  • 1
    @schrodiger, I'm glad it was useful. I now realize the q command is not even needed, sed ':a;${s/^/# /;s/\n/&# /g;};N;4,$D;ba' file is enough because N works like q if called from the last line of the file. Commented Nov 12, 2021 at 15:16

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.