请注意,我即将发布的此代码有目的地并不完美,如果目录中有文本文件但完整代码确实有这样的检查,则无法正常工作。但问题在于:
#!/bin/bash
for d in *; do
cd $d
done
产生:
./test: line 3: cd: 500: No such file or directory
./test: line 3: cd: 536: No such file or directory
./test: line 3: cd: 560: No such file or directory
./test: line 3: cd: 572: No such file or directory
./test: line 3: cd: out.txt: No such file or directory
./test: line 3: cd: prob1: No such file or directory
./test: line 3: cd: problem2: No such file or directory
./test: line 3: cd: README: No such file or directory
./test: line 3: cd: test: No such file or directory
其中500,536,560和572是应该能够打开的目录。如果我只做一张CD 500,那么我可以毫无问题地进入目录。但是当我在shell脚本中使用自动化过程时,它将无法工作。
好的,所以在进一步进入程序后我现在有了:
#!/bin/bash
cd "$1"
for d in */; do
(
cd "$d"
for file in $*; do
(
bla="$(head -4 $file|tail -1)"
cd ~cfb43/cs265/a1
echo $bla > out.txt
cd
cd "$1"
cd "$d"
)
done
cd "$1"
)
done
我收到:
head: error reading `/home/cfb43/cs265/a1': Is a directory
head: error reading `/home/cfb43/cs265/a1': Is a directory
head: error reading `/home/cfb43/cs265/a1': Is a directory
head: error reading `/home/cfb43/cs265/a1': Is a directory
head: error reading `/home/cfb43/cs265/a1': Is a directory
我想要做的就是进入一个目录并从文件中读取并获取第四行文本并将其打印到我文件夹中的out.txt。我不确定为什么这个代码卡在a1而不是至少500或类似的东西。任何进一步的帮助,我会非常好的
答案 0 :(得分:5)
因为您尝试进入下一个子目录而不离开前一个子目录。你可以做到
#!/bin/bash
for d in */; do
cd -- "$d"
# do some stuff
cd ..
done
或使用子shell
#!/bin/bash
for d in */; do
(
cd -- "$d"
# do some stuff
)
done
答案 1 :(得分:1)
你确定你在做什么:$ *扩展到参数$ 1 $ 2 .. $ {!#}
for file in $*; do
也许你想要:*扩展到当前目录中的文件
for file in *; do
另一种方法是永远不要改变目录:
for file in */*;do
head -4 "$file" | tail -1 >> ~cfb43/cs265/a1/out.txt
done
和另一种方法
head -4 | tail -1
sed n '4{p;q}'
使用awk
awk 'NR==4{print;exit}'
使用perl
perl -ne 'if($.==4){print;exit}'