Shell – Removing all spaces, tabs, newlines, etc from a variable

newlinessedshelltrwhitespace

This is the error I am getting and it's failing because of a variable whose value is supposed to be 2 (I am getting this using a select * from tabel).
I am getting spaces in that variable.

+ 0 != 
         2
./setjobs[19]: 0:  not found.

How do I remove all those spaces or a newline from that variable?
Can tr, sed, or anything help?

This what I am doing:

set_jobs_count=$(echo  "set heading off;
      select count(*) from oppar_db
      where ( oppar_db_job_name, oppar_db_job_rec ) in ($var) ;" | \
  sqlplus -s ${OP_ORA_USER}/${OP_ORA_PASS}@$OPERATIONAL_DB_NAME)

This works as suggested:

| sed 's/[[:space:]]//g'

But I still obtain a value like :

  set_jobs_count=
  2

Best Answer

The reason sed 's/[[:space:]]//g' leaves a newline in the output is because the data is presented to sed a line at a time. The substitution can therefore not replace newlines in the data (they are simply not part of the data that sed sees).

Instead, you may use tr

tr -d '[:space:]'

which will remove space characters, form feeds, new-lines, carriage returns, horizontal tabs, and vertical tabs.

Related Question