Piyush Baijal
Piyush Baijal

Reputation: 281

Replace all leading and trailing white spaces and tabs

My code is like below:

cat sample.txt

    line1    value1
line2    value2    
    line3    value3 

My code: It is removing spaces but not able to remove tabs.

sed 's/^[ \t]*//;s/[ \t]*$//' sample.txt

Upvotes: 0

Views: 1203

Answers (3)

glenn jackman
glenn jackman

Reputation: 246754

Non-sed answers:

perl -lpe 's/^\s*|\s*$//g' sample.txt
while read -r line; do echo "$line"; done < sample.txt

The last one is interesting: to preserve leading and trailing whitespace, you have to explicitly set IFS to the empty string. Compare

while      read -r line; do echo ">$line<"; done < sample.txt
# vs
while IFS= read -r line; do echo ">$line<"; done < sample.txt

Upvotes: 0

anubhava
anubhava

Reputation: 784958

In POSIX world [[:blank:]] would match both space and tab so you can do this:

sed 's/^[[:blank:]]*//;s/[[:blank:]]*$//' sample.txt

Upvotes: 4

captcha
captcha

Reputation: 3756

Code for GNU :

sed 's/^[ \t]*//;s/[ \t]*$//' file

Upvotes: 1

Related Questions