How to strip whitespace from a string in Unix shell script

I am reading a file and cutting out a column based on some logic. My problem is that I cannot cut the column with space.

This is the code for testing -

st="1|alalhabad|up|tushar|kesarwani|90|   mls   k|19990|india|420|24|m"
HardErrorCheckColumnValue=`echo $st | cut -d'|' -f7`
echo $HardErrorCheckColumnValue

      

The output should be -

   mls   k

      

But I am getting -

mls   k

      

How do I get it to not trim leading or trailing spaces? This should give space even if it only contains space.

+3


source to share


3 answers


You must use quotes around your variables:

HardErrorCheckColumnValue=$(echo "$st" | cut -d'|' -f7)
echo "$HardErrorCheckColumnValue"
   mls   k

      



Better to use $(...)

instead of the old fashioned back-tick to replace commands.

+5


source


awk Help you with this

$ cat file.dat
1|alalhabad|up|tushar|kesarwani|90|  mls ki |19990|india|420|24|m

$ awk -F"|" '{print "|"$7"|"}' file.dat
|  mls ki |
||

      

EDIT 2



If you echo from an st variable, there is a problem where some of the spaces disappear:

check the difference:

$ st="1|alalhabad|up|tushar|kesarwani|90|   mls   k|19990|india|420|24|m"

$ echo $st
1|alalhabad|up|tushar|kesarwani|90| mls k|19990|india|420|24|m  <-- ONE SPACE GONE

$ cat file.dat
1|alalhabad|up|tushar|kesarwani|90|  mls ki |19990|india|420|24|m

$ awk -F"|" '{print "|"$7"|"}' file.dat
|  mls ki |  <---- SPACE OK
||

      

+1


source


Protect your variable before printing it:

echo "$HardErrorCheckColumnValue"

      

Without a quote, it expands to echo mls k

, and with it, it expands toecho " mls k"

But as @Mat pointed out the damage already done. So refer to @anubhava answer :)

-1


source







All Articles