I need to extract (stdout is OK) a rectangle of text from a text file. A rectangle should be the text between lines l1 and l2 and columns c1 and c2.

I can already do this with a head, tail and cut in a nice pipe and am wondering whether there is a tool that can do it "all at once"(tm).

Any idea?


You could use sed, it is very flexible. For instance, to print lines 2 to 5, and 4 columns starting at column 3:

sed -n '2,5 s/^.\{3\}\(.\{1,4\}\).*$/\1/p'
  • -n means do not print the line if no match
  • 2,5 means only for lines 2 to 5
  • s/1/2/p means substitute 1 by 2 and print it
  • ^.\{3\} match at start of line (^) any character exactly 3 times
  • \( \) selects what we will output using \1 in replace part
  • .\{1,4\} select any character once up to 4 occurences
  • .*$ match any character up to the end of line

All together, this will do what you want.

The previous solution is missing lines with less than 4 characters.
A better solution is:

sed -n '2,5 s/^.\{0,3\}\(.\{0,4\}\).*$/\1/p'

This one will put empty line if the line is less than needed characters, by allowing 0 columns before output, and 0 columns in output.

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.