sed removing extra character from end

Hi,

Searching through forum I found "sed 's/[ \t]*$//'" can be used to remove trailing whitespaces and tabs from file. The command works fine but I see minor issue as below. Can you please suggest if I am doing something wrong here.

$ cat a.txt
upg_prod_test
upg_prod_new

$ cat a.txt |sed 's/[ \t]$//'
upg_prod_tes
upg_prod_new

In above example the sed is removing trailing character if word is terminating with "t".

Thanks for your time.

Looks like your sed doesn't like to interpret the escape sequence "\t"; other versions do.
If your shell allows for it, try

sed "s/[ "$'\t'"]$//" a.txt

or simply

sed 's/[  ]$//' a.txt
         ^--- use CTRL-V <TAB> for this char

.

Still the same issue.

$ sed "s/[ "$'\t'"]$//" a.txt
upg_prod_tes
upg_prod_new

$ sed "s/[ "$'\t'"]*$//" a.txt
upg_prod_tes
upg_prod_new

Not sure if I would be able to make use the second option suggested as the "sed" is part of a SH which is copied from another server using scp command line.

Thanks.

Another approach:

sed 's/[ \t]*$//' a.txt

Or us CTRL-V <TAB> for \t

Strange. Works in bash on linux and (Free)BSD.

cat file
upg_prod_test
upg_prod_new    

sed "s/[ "$'\t'"]$//" file
upg_prod_test
upg_prod_new

sed 's/[        ]$//' file
upg_prod_test
upg_prod_new

What's your shell?
Pls try (with CTRL-V <TAB>)

sed 'p;s/[      ]$//' file

and post result

1 Like

I am using KSH on AIX 6.1

spc=`printf '[ \t]'`
<a.txt sed 's/'"$spc"'$//'
1 Like

Try

TAB=$(printf "\011")
sed "p;s/[ $TAB]$//" file
sed 's/'"$spc"'*$//' a.txt

Worked for me .. Thanks !!

---------- Post updated at 08:41 AM ---------- Previous update was at 08:40 AM ----------

Thanks RudiC/MadeInGermany for your time :slight_smile:

A general solution that should work with any (POSIX) sed (and independent of the capabilities of the shell it runs in) would be:

sed 's/[[:blank:]]*$//' a.txt

Will it be able to remove tabs as well?

Yes.

1 Like