从数组的所有元素中删除空格

Remove spaces from all elements of an array

我的示例文件名为 'test.in',如下所示,前导和尾随空格:

 Hi | hello how | are you?
 I need | to remove | leading & trailing
 spaces |  where  ever   | it's located

我需要把元素用“|”隔开在以“\n”作为主要分隔符的数组中。

我希望数组中的每个元素都不应该有前导或尾随空格,只允许字符之间有空格。在将代码作为我的主要部署之前,我正在使用示例代码来测试结果。

示例脚本部分:

OIFS="$IFS"
IFS=$'\n'
while read LINE
do
IFS='|'
my_tmpary=($LINE)
echo ${my_tmpary[@]}
my_ary=`echo ${my_tmpary[@]} | awk '='`
echo ${my_ary[@]}
done < test.in

我不想使用循环来清理多余的空间。 我使用 sed、awk、tr 进行了试错法,但对我来说还没有成功。

my_ary[@]应该是这样的

Hi hello how are you?
I need to remove leading & trailing
spaces where ever it's located
sed -E 's/[\t]{1,}/ /g;s/^ *| *$//g;s/[ ]{2,}/ /g;s/ *\| */ /g;' test.in

应该这样做。所以:

$ my_ary=$(sed -E 's/[\t]{1,}/ /g;s/^ *| *$//g;s/[ ]{2,}/ /g;s/ *\| */ /g;' test.in)
$ echo "$my_ary"
Hi hello how are you?
I need to remove leading & trailing
spaces where ever it's located
This lines has many tabs

解决了你的问题。


注释 1. s/[\t]{1,}/ /g 将制表符即 \t 转换为空格。 2. s/^ *| *$//g 删除前导和尾随空格。 3. s/[ ]{2,}/ /g 将多个空格压缩为一个。 4. s/ *\| */|/g 删除 | 周围的空格 5. -E 允许使用带有 sed.

的扩展正则表达式

当默认 IFS 时,您可以(ab)使用读取将删除前导和尾随空格的事实:

while read -r line; do
  printf "%s\n" "$line" # Leading and trailing spaces are removed.
done < test.in

您可以选择 sed 来完成这样的任务:

sed 's/^[[:space:]]*\|[[:space:]]*$//g' test.in

在 AWK 中:

awk '{gsub(/^ *| *$|/,"",[=10=]); gsub(/ *\| *| +/," ",[=10=]); print [=10=]}' test.in

gsub(/^ *| *$|/,"",[=12=]) 删除前导和尾随 space, gsub(/ *\| *| +/," ",[=13=]) 将 space-pipe-space 组合和多个 space 替换为单个 space, print [=14=] 打印整个记录。 $0 可以像 @mona_sax 评论的那样被省略,但为了清楚起见,我把它留在了代码中。

当然可以循环,每个竖线分隔的字段分别修剪:

awk -F\| -v OFS=" " '       # set input field separator to "|" and output separator to " "
function trim(str) {
  gsub(/^ *| *$/,"",str);   # remove leading and trailing space from the field
  gsub(/ +/," ",str);       # mind those multiple spaces as well
  return str                # return cleaned field
} 
{
  for(i=1;i<=NF;i++)        # loop thru all pipe separated fields
    printf "%s%s", trim($i),(i<NF?OFS:ORS) # print field and OFS or  
}                                          # output record separator in the end of record
' test.in

.