Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

324
Views
Bash regexp: How to replace all non-whitespace characters with a letter?

I have a text file that contains a lot of whitespace and some other ASCII characters. I would like to use Bash (preferably via sed) to replace any non-whitespace characters in the file with the letter M. How would I go about doing this?

Thanks for helping.

edit: For the downvoters, I tried running this:

sed -i 's/[^\s]/M/g' file

and this:

sed -i 's/[^\s]/M/' file

but neither of them worked out too well. I'm a little unfamiliar with regex, so apologies if I'm doing something obviously wrong.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You could use POSIX character classes:

sed -i 's/[^[:space:]]/M/g' file

For example:

$ echo 'a b       c' | od -a                  
0000000   a  sp   b  sp  ht   c  nl
0000007
$ echo 'a b       c' | sed 's/[^[:space:]]/M/g' | od -a
0000000   M  sp   M  sp  ht   M  nl
0000007

Note:

  • The g flag to the s command, since you want to replace all matches in a line
over 4 years ago · Santiago Trujillo Report

0

Use tr

tr -c '[:space:]' M < file
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!