views:

238

answers:

5

Hi all,

I am using the following code to remove both leading and tailing spaces from all lines of a file A.txt

sed 's/^[ \t]*//;s/[ \t]*$//' ./A.txt > ./B.txt

The problem occurs on the lines where there is a t in the beginning or at the end. So say for example, the original line that starts with the string "timezone" becomes "imezone"

Can you please tell me what is happening here? and also if there is a known solution to the problem.

Thanks in advance.

+2  A: 

You might have better luck if you just use the whitespace character class:

sed -e 's/^\s*//' -e 's/\s*$//' A.txt > B.txt
jheddings
Unfortunately if his sed is so old it doesn't understand \t, it probably doesn;t understand \s either.
Chris Dodd
Good point... I hadn't considered that.
jheddings
+2  A: 

newer versions of sed understand \t but older versions may not have. You may be better off replacing \t with a literal tab (CTRL-V will give you that)

What version of sed are you using on what system? (sed --version for GNU sed)

Phil
+6  A: 

Some older versions of sed don't understand C-style escape characters such as \t and treat that as two characters, '\' and 't'. You can avoid the problem by using a literal tab character -- if you're typing this directly into the shell, type Ctrl+V Tab.

Chris Dodd
+1 for `Ctrl+V Tab`. I never known that. :-D
NawaMan
After some googling, I found that you can also use `Ctrl+v Ctrl+l` for tab. (work on Ubuntu atleast)
NawaMan
@NawaMan, are you sure that's not CTRL-v, CTRL-i ? CTRL-i is the tab character.
paxdiablo
+2  A: 

Another alternative, using whitespace character classes, if your variety of sed doesn't support \s:

sed 's/^[[:space:]]*//;s/[[:space:]]*$//'
martin clayton
+1  A: 

gawk

awk '{gsub(/^[[:space:]]+|[[:space:]]+$/,"")}1' file
ghostdog74