I usually go to stackexchange when I face programming terminal and I spend most of time trying to append four spaces before my pasted programming code.

Is there any faster way to do it from a terminal? What would you do?

  • 4
    You can just highlight the code and click the { } button on the S.E. editor interface to do the indent. – goldilocks Nov 17 '14 at 15:44
  • @goldilocks O, wow, I never knew that :o – Bernhard Nov 17 '14 at 15:49
  • 1
    Ctrl-K does this from the keyboard. Select the region you want to format as code, then type this keyboard shortcut. – tripleee May 30 '17 at 15:37
up vote 9 down vote accepted

Simply use sed,

sed 's/^/    /' file

This appends four spaces before each line. Add an inline edit option -i to save the changes to the specified file.

sed -i 's/^/    /' file

Through awk,

awk '{sub(/^/, "    ", $0)}1' file

OR

awk '{print "    "$0}' file
  • I think the first sed command would be more than sufficient. Here, you typically don't want -i and awk seems overly complicated. Maybe add that ^ matches the beginning of the line. – Bernhard Nov 17 '14 at 15:49

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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