How to delete each line in a text file in batches under mac ^M

Original link: https://blog.kelu.org/tech/2023/05/30/how-to-remove-m-from-each-line-in-text-files-in-macos.html

I compared the code sent by my windows colleague from Mac, git diff shows that many files have changed, and each line is displayed as modified, which seriously affects the diff function.

Initially, we tried to use the sed command to strip the “^M” character at the end of each line, but it didn’t work as expected:

 find . -type f -name "*.txt" -exec sed -i '' $'s/ \r $//' {} \; find . -type f -name "*.txt" -exec dos2unix {} +

Turning to Perl solves this problem:

 find . -type f -name "*.txt" -exec perl -pi -e 's/\r$//' {} \;

explain:

  • Use the find command to recursively search for text files in the current directory and its subdirectories.
  • The -type f option ensures that only regular files are matched.
  • -name "*.txt" option filters files with a “.txt” extension.
  • The -exec option is used to execute a Perl command on each matching file.
  • perl -pi -e is the Perl command to perform in-place editing on files.
  • The regular expression 's/\r$//' matches the “^M” character ( \r ) at the end of each line and replaces it with an empty string.

Notice:

  • Before making any modifications to the files, it is recommended to back up the files to prevent accidental data loss.
  • Remember to adjust the commands and options according to your specific requirements and file locations.

This article is transferred from: https://blog.kelu.org/tech/2023/05/30/how-to-remove-m-from-each-line-in-text-files-in-macos.html
This site is only for collection, and the copyright belongs to the original author.