[英]How to cut a space from a string in a Unix shell script
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.
它应该给空间,即使它只包含空间。
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. 最好使用
$(...)
而不是旧式的后退来进行命令替换。
awk Will help you with that awk会帮助你
$ 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 编辑2
If you echo the st variable there is a problem there, where some spaces disapear: 如果你回显st变量那里有一个问题,一些空格消失:
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
||
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"
没有引用它会扩展为
echo mls k
,而随着它被扩展为echo " mls k"
But as pointed out @Mat, damage already done. 但正如@Mat指出的那样,伤害已经完成了。 So refer to @anubhava answer :)
所以请参考@anubhava的答案:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.