-1

Is it possible to remove multiple spaces from a text file and save the changes in the same file using awk or grep?

Input example:
aaa     bbb  ccc
   ddd    yyyy

Output I want:
aaa bbb ccc
ddd yyyy
  • 1
    Does this answer your question? [How to remove extra spaces in bash?](https://stackoverflow.com/questions/13092360/how-to-remove-extra-spaces-in-bash) – Wiktor Stribiżew Mar 31 '20 at 07:56
  • 1
    @nuclearwinter27 : `grep` does not modify any file. It reads files and writes to stdout. `awk` programs can create a file, but I am not aware that awk offers anything to update a file in-place; at least it was not designed for this. Some languages and tools (for instance `sed`, `ruby`, `perl`) make this task easy by simulating "in-place" editing. – user1934428 Mar 31 '20 at 08:39

2 Answers2

2

Simply reset value of $1 to again $1 which will allow OFS to come into picture and will add proper spaces into lines.

awk '{$1=$1} 1' Input_file


EDIT: Since OP mentioned that what if we want to keep only starting spaces then try following.

awk '
match($0,/^ +/){
  spaces=substr($0,RSTART,RLENGTH)
}
{
  $1=$1
  $1=spaces $1
  spaces=""
}
1
'  Input_file
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
2

Using sed

sed -i -E  's#[[:space:]]+# #g' < input file 

For removing spaces at the start

sed -i -E  's#[[:space:]]+# #g; s#^ ##g' < input file

Demo:

$cat test.txt
aaa     bbb  ccc
   ddd    yyyy

Output I want:
aaa bbb ccc
ddd yyyy
$sed -i -E  's#[[:space:]]+# #g' test.txt 
$cat test.txt
aaa bbb ccc
 ddd yyyy

Output I want:
aaa bbb ccc
ddd yyyy
$

Digvijay S
  • 2,665
  • 1
  • 9
  • 21