0

My googlefu is failing me. I have a bunch of variables I read it from a CSV where I want to strip whitespace. I could

variable1="$(echo -e "${variable1}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
variable2="$(echo -e "${variable2}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
variable3="$(echo -e "${variable3}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"

but then I'm copying in and editing this for every variable change. It seems to me, from other languages, there should be a way to do a simple for loop that applies to the variables as named and strips the whitespace, but I can't figure out exactly how to do that.

for $i in variable1 variable2 variable3
do
$i=$(echo -e "${$i}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
done

but this doesn't work as far as I can tell. What I want to do is loop over all the variables, strip whitespace, but not have to manually type out each variable name in the script.

4

1 回答 1

3

尝试以下操作:

# Sample values that need trimming.
variable1='  a  '
variable2='      b  c  '
variable3='        sadf sdf sdf     '

for name in ${!variable*}; do
  # Trim leading and trailing whitespace.
  read -r $name <<<"${!name}"
  # Print result
  echo "Variable $name now contains: [${!name}]"
done

该解决方案依赖于变量间接即通过另一个包含目标变量名称的变量间接引用变量的能力。

请注意,变量间接有其缺陷(请参阅链接),并且通常有更好的解决方案,例如,通过使用数组。

  • ${!variable*}扩展为名称以 . 开头的所有已定义变量的名称variable
  • ${!name}扩展为名称存储在 variable 中的变量的值$name
  • read -r,通过读入单个变量,隐式修剪前导和尾随空格。
    • -r确保\字符。在输入中留下单独的,这通常是你想要的。
于 2015-05-13T18:46:54.233 回答