A very similar question has probably been asked many times, e.g. How to insert text before the first line of a file?

But all those solutions add a tab, then a line return to the beginning of the file. I want to add just a tab to the start of the first line.. how to do that??

Thanks very much


One way to do it, assuming a shell smart enough to know about <(...) construction, and an echo smart enough to know what to do with -n and -e options:

cat <(echo -ne '\t') file


( printf '\t'; cat file ) >new_file

If you must do it with sed, assuming your sed is smart enough to know about \t:

sed '1s/^/\t/' file

But that's a lot more problematic, depending on the implementation of your sed. It also doesn't work for empty files.

| improve this answer | |

Use ex, which is specified by POSIX. Add a tab-newline sequence at the start of the file, then run ex's join command.

This works whether the file is empty or not, and should be fully portable to any UNIX or Linux system.

(Note that if the file begins as an empty file, the contents after this command will be a tab character and a newline. A file without a terminating newline is technically not actually a text file.)

printf '0a\n\t\n.\n1j!\nx\n' | ex myfile.txt

If you run the printf command by itself you can see the instructions that are getting passed to ex:

$ printf '0a\n\t\n.\n1j!\nx\n'


Note that there is a single tab character in the otherwise blank line above.

| improve this answer | |
sed '1 s/^/\t/' < textfile.txt
| improve this answer | |

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.