Reputation: 43
I am reading a file and cutting a column based on some logic. My issue is I am not able to cut a 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 make it not trim the leading or trailing spaces? It should give space, even if it contains only space.
Upvotes: 3
Views: 267
Reputation: 2768
awk Will help you with that
$ 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 the st variable there is a problem there, where some spaces disapear:
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
||
Upvotes: 1
Reputation: 785246
You must use quotes around your variables:
HardErrorCheckColumnValue=$(echo "$st" | cut -d'|' -f7)
echo "$HardErrorCheckColumnValue"
mls k
Better to use $(...)
instead of old fashioned back-tick for command substitution.
Upvotes: 5
Reputation: 4058
Protect your variable before printing it:
echo "$HardErrorCheckColumnValue"
Without the quote it gets expanded to echo mls k
, while with it get's expanded to echo " mls k"
But as pointed out @Mat, damage already done. So refer to @anubhava answer :)
Upvotes: -1