XuLaLa.Tech

首页客户端下载Windows 使用V2Ray 教程SSR 教程Clash 教程

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

2025.04.09

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

文章目录

  • 1 sed命令去掉空格
  • 2 AWK命令去掉空格
  • 3 TR去掉空格
  • 4 字符串替换掉空格
  • 5 cut去掉空格

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-
© 2010-2022 XuLaLa 保留所有权利 本站由 WordPress 强力驱动
请求次数:69 次,加载用时:0.665 秒,内存占用:32.19 MB