關於循環嵌套使用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