Categories: Shell编程

shell bash中如何去掉字符串中空格?

如果你经常写bash脚本,习惯用命令行操作或者命令来处理一些文本文件,不可避免就会遇到需要去掉字符串空格的场景。在bash中可以使用sed命令、awk命令、cut命令、tr命令来去掉空格。

sed命令去掉空格

去掉制表符和空格

output="=    This is    a test    ="

echo "=$(sed -e 's/^[ \t]*//' -e 's/\ *$//g'<<<"${output}")="
## more readable syntax  #
echo "=$(sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'<<<"${output}")="

AWK命令去掉空格

output="    This is a test    "
echo "=${output}="

## Use awk to trim leading and trailing whitespace
echo "${output}" | awk '{gsub(/^ +| +$/,"")} {print "=" $0 "="}'

TR去掉空格

echo "GNU     \    Linux" | tr -s ' '

字符串替换掉空格

output="    This is a test    "
output=${output// /}

cut去掉空格

echo $output |cut -d " " --output-delimiter=""  -f 1-
5.0
04
Supervisor 的 Event & Listener进程监控告警
Stable Diffusion公司开源大语言模型StableLM来了!
嘻嘻

嘻嘻IT: 笔者是一个工作七八年的程序猿老鸟,从事涉及的技术栈主要包括PHP、Linux、Devops等,喜欢研究新技术,尝试新技术,提升技术自动化和开发效率,致力于write less,do more! 技术每年都会层出不穷,领域划分的越来越细,不可能学习所有的东西,保持对技术的好奇心,理解技术中核心思想,做一个有深度,有思想的开发!

Recent Posts

PHP Composer如何安装?

PHP Composer是PH…

1天 ago

MacOS上Missing xcrun的问题

在使用MacOS进行编程或开发…

1天 ago

CodeGeeX是一款基于大模型的全能AI编程助手

CodeGeeX是一个面向开发…

2天 ago

MySQL覆盖索引详解

在数据库性能优化中,索引是一个…

2天 ago

后端程序员必备:SQL优化的20条建议

SQL优化查询对于后端程序员来…

2天 ago