我的问题是,我读了文件,并得到了字符串数组,但每个我的字符串在这些末端空间,我需要将其删除。每行有空间不同的号码。我怎样才能做到这一点?
现在,我可以从每个字符串中删除所有的空格,它看起来像:
我的代码:
index=0
while read name; do
get_user_group_from_file[$index]="${name//[[:space:]]/}"
index=$(($index+1))
done < "${FILE}"
与你的方法的问题是参数扩展代码删除从给定的输入行中的所有空间。对于如看到
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}"
我相信,你只需要改变线路有
get_user_group_from_file[$index]="${name// *$/}"
您可以输出去除尾随空格这样的文件:
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
通过自身消除拖尾和先行空白字符。也可以让反斜杠字符进行转义。采用:
while IFS= read -r name
更多关于该主题可以发现here。
到文件读入的阵列而不尾部空格,使用:
mapfile -t get_user_group_from_file < <(sed 's/[[:space:]]*$//' file)