Remove whitespace in bash using sed

I have a file that contains a number followed by the file path on each line for a large number of files. So it looks like this:

      7653 /home/usr123/file123456

      

But the problem is that there are 6 blank spaces in front of that which throws away the rest of my script. I have included a line that produces it below:

cat temp | uniq -c | sed 's/  */ /g' > temp2

      

I've narrowed it down to a command uniq

that creates unnecessary white space. I tried to implement a command sed

to remove the space, but for some reason it removes everything but one. How can I change my operator sed

or my operator uniq

to get rid of these spaces? Any help would be greatly appreciated!

+3


source to share


2 answers


To remove all leading spaces use:

sed 's/^ *//g'

      

To remove all leading spaces of any type:



sed 's/^[[:space:]]*//g'

      

The character ^

matches only at the beginning of the line. Because of this, the above leaves any spaces not at the beginning of the line alone.

+5


source


Breaking current pattern sed / * // g: The search pattern, '*', matches one space, followed by zero or more spaces. The replacement pattern, '', is a single space. The result is to find any set of one or more spaces and replace it with a single space, and therefore remove all but one space. To remove everything, you can simply make your replacement pattern with an empty string, '': sed 's / * // g'

Note, however, that 'g' makes it global so that the space between the number and the file is also removed. If you just want to remove the leading space, you can simply remove g. You can also use the quantifier +, which means "at least one", and not *, which means "at least zero". That would leave you with: sed 's / \ + /'



ETA: As John1024 points out, you can also use the ^ anchor to indicate the start of a line, and the \ s wildcard to indicate any whitespace characters instead of just spaces: sed 's / \ s \ + //

0


source







All Articles