sed -e 's/word1/word2/' -l 3 output > output2

I'm testing this command. I expected 3 characters for each line. But, it doesn't work. output2 has the same line breaks as output. Have I misunderstand line-wrapping??

  • 1
    And where is the sample texts to work on, please provide that! – George Udosen Dec 14 '17 at 12:54
  • That was just a bunch of random texts of several lines. – Smile Dec 14 '17 at 13:53

In short... yes you have misunderstood line-wrapping slightly ;)

-l N, --line-length=N
       specify the desired line-wrap length for the `l' command

So, it only works with the l command:

l      List out the current line in a ``visually unambiguous'' form.
l width
       List out the current line in a ``visually unambiguous'' form,
       breaking it at width characters.  This is a GNU extension.

If you want the output three characters per line, you could use this:

sed -nl 4 's/word1/word2/;l' output > output2

or this in GNU sed:

sed -n 's/word1/word2/;l 4' output > output2

Note that a trailing backslash (to escape the line break) is appended if there is not actually a new line (end-of-line is indicated by $ characters). We need to use the -n flag, because the l command is for viewing rather than editing, like the = command, and the line will appear as normal after l has output it in the requested form, unless suppressed by -n.

You might get more like what you actually want by simply breaking the file after every three characters:

sed 's/word1/word2/; s/.../&\n/g' output > output2

or to split after, say, 10 characters:

sed -r 's/word1/word2/; s/.{10}/&\n/g' output > output2
| improve this answer | |
  • Thanks for the detailed answer. After reading documentation and your answer I wonder why I don't deduce the command combination like you did. I think the reason is that I don't have the basic knowledge to make scripts. I can guess what it means 's/word1/word2/;l', but I don't want to rely on the guess. I want to be precise. What should I do to be proficient with scripts like this example?? – Smile Dec 14 '17 at 13:52
  • 1
    @Smile oh, just keep practising :) Here's a resource I like for sed with examples. – Zanna Dec 14 '17 at 13:55
  • I'm reading gnu.org/software/sed/manual/sed.html#Introduction. After that I'm gonna read the resource you provide. Is it too much? – Smile Dec 14 '17 at 14:06
  • 2
    @Smile just stop when you get bored :) – Zanna Dec 14 '17 at 14:20

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.