Linux replace all spaces

Replace all white spaces with commas in a text file

I need to replace all white spaces inside my text with commas. I’m currently using this line but it doesn’t work: I get as output a text file which is exactly the same of the original one:

5 Answers 5

Edit: To exclude newlines in Perl you could use a double negative ‘s/[^\S\n]+/,/g’ or match against just the white space characters of your choice ‘s/[ \t\r\f]+/,/g’ .

This will replace any horizontal whitespace with a comma. Any repeated whitespace will only be replaced with a single comma.

The issue with your command,

The [:blank:] is a bracketed expression matching one of the characters : , a , b , k , l , or n . If you want to match one of the characters in the POSIX character class [:blank:] , use [[:blank:]] .

The + is an extended regular expression modifier. The sed utility uses basic regular expressions, and the + would match a literal + character. To get the same effect in a basic regular expression, use \ <1,\>, or, in this particular expression, use [[:blank:]][[:blank:]]* instead.

In short, your corrected sed expression would be

As others have pointed out, and assuming single byte ASCII characters in the text, it may be more efficient to use tr in this case, as it’s a simple transliteration of one set of characters to another. Either one of the following two tr commands would solve the issue:

where [,*] means «as many commas as is needed for this set to match the number of characters in the first set», or

The -s option to tr causes multiple consecutive commas to be «squeezed» into single commas.

Источник

Replace whitespaces with tabs in linux

How do I replace whitespaces with tabs in linux in a given text file?

11 Answers 11

Use the unexpand(1) program

I think you can try with awk

or SED if you preffer

or a simplified version of the tr solution sugested by Sam Bisbee

Using Perl:

better tr command:

This will clean up the output of say, unzip -l , for further processing with grep, cut, etc.

Download and run the following script to recursively convert soft tabs to hard tabs in plain text files.

Place and execute the script from inside the folder which contains the plain text files.

Читайте также:  Windows 10 домашняя не видит принтер

Example command for converting each .js file under the current dir to tabs (only leading spaces are converted):

You can also use astyle . I found it quite useful and it has several options too:

Using sed:

If you are talking about replacing all consecutive spaces on a line with a tab then tr -s ‘[:blank:]’ ‘\t’ .

If you are talking about replacing all whitespace (e.g. space, tab, newline, etc.) then tr -s ‘[:space:]’ .

If you are talking about fixing a tab-damaged file then use expand and unexpand as mentioned in other answers.

Источник

Replace all spaces in a certain part UNIX

Hi all I’m trying to replace all spaces beginning in certain part of my file. I tried to do it but I can’t make it to start in a certain part.

i tried this sed «s/\s/_/g» file_1.txt but all of the spaces turn into underscore.

5 Answers 5

If you want the substitution to happen only after «List of Dogs», try

The command b means «branch» (to the end of the script, i.e. bypass the substitution) and the address range specifies this action for the first line through the first line matching the regex.

If you want the substitution happen only after the : , use something like this:

The substitution is restricted from a line containing : until the end of the file $ .

Given your initial input file.txt :

You can try this:

Explanation

  • sed commands can be split by ;
  • first part starts with getting an address, which is the form range start,range end . Finds the line that List of Dogs starts at. And $ specifies last line of file, for the range end part of this syntax
  • so just for this address range, your search and replace command is done: $s/\s/_/g
  • but unfortunately the command also replaced and resulted in List_of_Dogs: so second command s/List_of_Dogs/List of Dogs/g is just a workaround to convert it back

You have the answer and you don’t know it =)

You say you want to replace the spaces, but you have not said what you want to replace them with. I suspect, you want to replace them with a no-space character, right?

or referencing the space with \s the following should also work

The syntax is basically

I hope that helps.

keep it simple, obvious, robust, portable, etc. and just use awk:

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

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Читайте также:  Как продлить лицензию windows 10 ltsc

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Replace multiple spaces with one using ‘tr’ only

I have a file, f1.txt :

The number of spaces is not fixed. What is the best way to replace all the white spaces with one space using only tr ?

This is what I have so far:

But the output is:

But I want it to look like this:

Please try and avoid sed .

6 Answers 6

With tr , use the s queeze repeat option:

Or you can use an awk solution:

When you change a field in record, awk rebuild $0 , takes all field and concat them together, separated by OFS , which is a space by default.

That will squeeze sequences of space and tabs (and possibly other blank characters depending on the locale and implementation of awk ) into one space, but also remove the leading and trailing blanks off each line.

If you want to squeeze «white space» you will want to use tr’s pre-defined character sets «:blank:» (horizontal whitespace tab and space) or «:space:» (verical whitespace) :

Examples were run on Red Hat 5 (GNU tr).

In my case I wanted to normalize all whitespace to a single space so I could rely on the space as a delmitter.

As pointed out by dastrobu’s second comment I missed the wording in the man page:

This allows us to eliminate the first tr. Kudo’s to scott for his patiences in the face of my denseness.

Before, parsing port from Redis config. file:

After, with SET2 being specified with the squeeze:

Demonstrate where squeeze alone fails when successive mixed characters which fall into the [:blank:] character class are involved:

Note: My two string fields in the printf format are separated by 1 space, 1 tab, 1 space. After the squeeze this sequence still exists. In the output of the Octal dump this is represented by ascii sequence 040 011 040.

Источник

Replace spaces in all files in a directory with underscores

I have found some similar questions here but not this specific one and I do not want to break all my files. I have a list of files and I simply need to replace all spaces with underscores. I know this is a sed command but I am not sure how to generically apply this to every file.

I do not want to rename the files, just modify them in place.

Edit: To clarify, just in case it’s not clear, I only want to replace whitespace within the files, file names should not be changed.

Читайте также:  Драйвер hdmi для windows 10 64 bit amd

3 Answers 3

find grabs all items in the directory (and subdirectories) that are files, and passes those filenames as arguments to the sed command using the <> \; notation. The sed command it appears you already understand.

if you only want to search the current directory, and ignore subdirectories, you can use

This is a 2 part problem. Step 1 is providing the proper sed command, 2 is providing the proper command to replace all files in a given directory.

Substitution in sed commands follows the form s/ItemToReplace/ItemToReplaceWith/pattern , where s stands for the substitution and pattern stands for how the operation should take place. According to this super user post, in order to match whitespace characters you must use either \s or [[:space:]] in your sed command. The difference being the later is for POSIX compliance. Lastly you need to specify a global operation which is simply /g at the end. This simply replaces all spaces in a file with underscores. Substitution in sed commands follows the form s/ItemToReplace/ItemToReplaceWith/pattern , where s stands for the substitution and pattern stands for how the operation should take place. According to this super user post, in order to match whitespace characters you must use either just a space in your sed command, \s , or [[:space:]] . The difference being the last 2 are for whitespace catching (tabs and spaces), with the last needed for POSIX compliance. Lastly you need to specify a global operation which is simply /g at the end.

Therefore, your sed command is

However this only accomplishes half of your task. You also need to be able to do this for every file within a directory. Unfortunately, wildcards won’t save us in the sed command, as * > * would be ambiguous. Your only solution is to iterate through each file and overwrite them individually. For loops by default should come equipped with file iteration syntax, and when used with wildcards expands out to all files in a directory. However sed’s used in this manner appear to completely lose output when redirecting to a file. To correct this, you must specify sed with the -i flag so it will edit its files. Whatever item you pass after the -i flag will be used to create a backup of the old files. If no extension is passed ( -i » for instance), no backup will be created.

Therefore the final command should simply be

Which looks for all files in your current directory and echos the sed output to all files (Directories do get listed but no action occurs with them).

Источник

Оцените статью