从字符串末尾删除空格

时间:2019-02-01 10:05:56

标签: bash shell

我的问题是我读取了一个文件并得到了字符串数组,但是我的每个字符串末尾都有空格,我需要将其删除。每行具有不同数量的空格。我该怎么办?

现在,我可以删除每个字符串中的所有空格,如下所示:

我的代码:

index=0
while read name; do
    get_user_group_from_file[$index]="${name//[[:space:]]/}"
    index=$(($index+1))
done < "${FILE}"

3 个答案:

答案 0 :(得分:2)

您的方法存在的问题是参数扩展代码从给定的输入行中删除了 all 个空格。例如见

str='line has spaces'
echo "${str//[[:space:]]/}"
linehasspaces

要仅删除最后一个,请对bash提供的extglob使用不同的构造

str='line has 4 spaces last    '
echo "${str%%+([[:space:]])}"

所以您的整个脚本应该像

#!/usr/bin/env bash

shopt -s extglob

while read -r name; do
    get_user_group_from_file[$index]="${name%%+([[:space:]])}"
    index=$(($index+1))
done < "${FILE}"

答案 1 :(得分:0)

您可以输出带有删除后缀空格的文件,如下所示:

sed 's/[[:space:]]*$//' "$file"

示例:

> echo "123   " > file
> echo "+$(cat file)+"
+123   +
> echo "+$(sed 's/[[:space:]]*$//' file)+"
+123+

和另一个示例:

> echo "123      " > file
> echo "+$(cat file)+"
+123      +
> sed -i -e 's/[[:space:]]*$//' file
> echo "+$(cat file)+"
+123+

或从保存在变量中的字符串中将其删除:

sed 's/[[:space:]]*$//' <<<"$line"

示例:

> string="alallal    ";
> string=$(sed 's/[ ]*$//' <<<"$string")
> echo "+${string}+"
+alallal+

[[:space:]]*与一个或多个空格字符(制表符,空格)匹配。如果只需要空格,请将其替换为[ ]*$用于指示行尾。

要获取文件中的行数,请使用wc -l

index=$(wc -l < "$FILE")

请注意:

while read name 

通过iteself删除尾随和前导的空白字符。还允许反斜杠转义字符。使用:

while IFS= read -r name

有关该主题的更多信息,请参见here

要将文件读入数组而不留空格,请使用:

mapfile -t get_user_group_from_file < <(sed 's/[[:space:]]*$//' file)

答案 2 :(得分:0)

我相信您只需要在此处更改一行

get_user_group_from_file[$index]="${name// *$/}"