2019年10月27日 星期日

[Linux 文章收集] Bash - How to trim string

Source From Here
How-To
You can use a bash parameter expansionsedcut and tr to trim a string.

Bash parameter expansion
Let's use bash parameter expansion to remove all whitespace characters from the variable foo:
- test1.sh
  1. #!/bin/sh  
  2. foo="Hello    world."  
  3. echo "${foo//[[:space:]]/}"  
Execution result:
# ./test1.sh
Helloworld.


Using sed command to trim the front/back space
To remove only space characters before and after string use sed:
- test2.sh
  1. #!/bin/sh  
  2. foo="      Hello    world.    "  
  3. echo "${foo}" | sed -e 's/^[[:space:]]*//'  
Execution result:
# ./test2.sh
Hello world.

Using xargs to remove space
Easy to use and remember way how to remove whitespaces before and after word:
- test3.sh
  1. #!/bin/sh  
  2. foo="      Hello    world.    "  
  3. foo_remove_space=`echo ${foo} | xargs`  
  4. echo "foo_remove_space='${foo_remove_space}'"  
Execution result:
# ./test3.sh
foo_remove_space='Hello world.'


Supplement
Split string by delimiter and get N-th element
Linux 系統 xargs 指令範例與教學

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...