我编写了下一个测试shell脚本:
#!/bin/sh
IFS=$'\n'
for d in `find . -name *.cue -print0 | xargs -0 -n1 dirname | sort --unique`
do
unset IFS
echo "$d"
IFS=$'\n'
done
unset IFS如果在bash中执行条件的find命令,就会获得如下内容:
./[FLAC] Destination Goa - The Sixth Chapter (CD)/CD2
./[FLAC] Eat Static - Implant - (CD)
./[FLAC] Elysium - Dance For The Celestial Beings (CD)
./[FLAC] Elysium - Monzoon 1996 (CD)
./[FLAC] Etnica - The Juggeling Alchemists Under The Black Light(包含提示文件的文件夹的名称)
在shell脚本中,我希望使用每个文件夹循环,但是,当然,如果我不重新定义IFS,出现的情况会用空格中断:
Experience
4
./[FLAC]
VA
-
Trancentral
Five
A
Sonic
Initiation
./[FLAC]
VA
-
Trancentral在另一台计算机(一台MacOS)中,我解决了使用此命令IFS=$'\n'将IFS更改为断线的问题,但在我的家用计算机( Ubuntu )中,循环中断时出现"n":
tra
ce - A Trip To Psychedelic Tra
ce (CD)/CD1
./[FLAC] VA - Ta
tra
ce - A Trip To Psychedelic Tra
ce (CD)/CD2
./[FLAC] VA - Tech
o Tra
ce Ma你知道发生了什么事吗?为什么计算机之间的行为不同?谢谢。
发布于 2014-04-12 16:00:25
您可以将IFS设置为这样的换行符:
IFS="
"$'\n'是zsh 93/bash/zsh语法,但不是POSIX语法。在大多数当前系统中,#!/bin/sh指向POSIX外壳(尽管POSIX不需要这样做,Solaris 9,10是例外)。
不管这个shell是否碰巧理解了$'\n',您都不应该依赖它。如果您想使用$'\n',请将其改为#!/bin/bash或其他shell之一。
在Ubuntu和debian以及衍生产品上,/bin/sh指向dash。与其他发行版一起,它指向/bin/bash --posix ( posix模式下的bash).
另一点要注意的是,如果取消IFS,则不会返回到以前的状态,即包含空格、TAB和换行符的IFS。通过取消IFS,字段分割就像IFS包含一个空格、一个TAB和一个换行符一样,所以一切看起来都很好。
取消IFS可能会引起并发症,但是,如果这与常规实践相结合的话。
unset IFS # Unset the IFS variable so it does not exist
oldIFS=$IFS # The old state is supposedly saved
IFS=: # IFS is set to some string
IFS=$oldIFS # Now IFS is set to the empty string, which means no field
# splitting is performed at all发布于 2014-04-12 09:22:22
你根本不需要循环。这应该是你想做的事:
find . -name *.cue -print0 | xargs -0 -n1 dirname | sort --unique如果您真的想遍历结果,for
while IFS= read -r line; do
printf '%s\n' "$line"
done < "$file"或
my_script | while IFS= read -r line; do
printf '%s\n' "$line"
done回到关于在文字n字符上拆分的问题,您的Ubuntu机器上的/bin/sh可能不支持 bashism。
https://stackoverflow.com/questions/23027637
复制相似问题