嵌套for in循环组合cat方式文件中包含空格问题

关于循环嵌套使用for循环的空格问题

原创不易,转载请注明

需求:

现有两个功文件,需要将文件拼接

[root@localhost ~]# cat name 
111
222 223
333
444
555 556
666
777
888
999 990
[root@localhost ~]# Parameter
aaa
bbb
ccc
ddd
eee
fff
ggg

需要将将name和Parameter两个文件拼凑成"111_aaa"、"111_bbb"的样式,将name跟Paremeter每个都拼接

我使用了for循环嵌套

for w in $(cat name);do
    for y in $(cat Parameter);do
        echo "$w"_"$y" >> test;
    done
done

本以为是小问题,发现结果不对,最后发现是空格的问题,于是在脚本里加了OFS=$\n,结果依然不对


解决方法一:

将IFS="\n"和IFS='\n'只会将两个文件内容相加,并不会得到想要的结果。需要在循环前就将IFS执行并运用

for in循环是读取cat的文件,而cat文件却包含了空格这个分隔符,这里涉及到了shell的域分隔符即(IFS),默认是空格回车和tab,所以这里需要指定IFS,并在循环执行前解析

#!/bin/bash
IFS=$'\n'
for w in $(cat name);do
    for y in $(cat Parameter);do
        echo "$w"_"$y" >> test;
    done
done
小结
$ man bash
NAME
       bash - GNU Bourne-Again SHell

       ...


       Words of the form $'string' are treated specially.  The word expands to
       string, with backslash-escaped characters replaced as specified by  the
       ANSI  C  standard.  Backslash escape sequences, if present, are decoded
       as follows:
              \a     alert (bell)
              \b     backspace
              \e
              \E     an escape character
              \f     form feed
              \n     new line
              \r     carriage return
              \t     horizontal tab
              \v     vertical tab
              \\     backslash
              \'     single quote
              \"     double quote
              \nnn   the eight-bit character whose value is  the  octal  value
                     nnn (one to three digits)
              \xHH   the  eight-bit  character  whose value is the hexadecimal
                     value HH (one or two hex digits)

Words of the form $'string'


解决方法二:

[root@localhost ~]# awk 'FNR==NR{c=FNR;a[c]=$0;next}{for(n=1;n<=c;++n)print $0"_"a[n]}' Parameter name

思路解析

利用awk的FNR记录Parameter文件的每一行,以行号为下标,记录为数组a,因为awk的数组顺序是随机的,所以需要使用循环将数组取出;按序取出name文件的内容,将每行内容与数组的内容组合输出


解决方法三:

使用read命令
read命令将参数读取记录,这样就避免了for循环中的分隔符问题PS都传到了变量里,还怕甚?

while read w;do
    while read y;do
        echo "$w"_"$y" >> test
    done < Parameter
done < name
posted @ 2017-09-24 15:26  陈浩然201  阅读(4649)  评论(0编辑  收藏  举报