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
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 to share