How can I trim the contents of a text file?

12,437

Assuming you want to remove all spaces and newlines, not just the last newline, you can use tr:

tr -d '[[:space:]]' < file > file.trimmed

Or, more precisely:

tr -d '\t\n ' < file > file.trimmed
Share:
12,437

Related videos on Youtube

Lawrence
Author by

Lawrence

Updated on September 18, 2022

Comments

  • Lawrence
    Lawrence over 1 year

    I want to remove all "blank" characters from the very beginning and the very end of a text file, including \n if exists. (basically mimicking the behaviour of trim() function of most programming languages, if the "file" was a big string).

    • Admin
      Admin about 6 years
      Can you provide a sample of the contents of the file?
    • Admin
      Admin about 6 years
      Each line, or just the very beginning and end?
    • Admin
      Admin about 6 years
      Just on the definition tack, I believe POSIX requires a newline at the end of a file in order to be called a “text” file. Just FYI.
    • Admin
      Admin about 6 years
      Jeff: the very beginning and end. (main description updated)