【发布时间】:2015-03-25 12:05:39
【问题描述】:
我正在编写一个 bash 脚本,它允许我从文件中获取一定数量的文本,并在此之前为文件列表添加一些其他文本。
directory=$(pwd)
for f in *test.txt
do
filename=$(basename $f .txt)
printf "%%sum=4 \n"> input.temp
printf "file=$directory"/"$filename".txt" \n">> input.temp
printf "some commands \n">> input.temp
printf "\n" >> input.temp
printf "description \n">> input.temp
sed -n "/0 1/,$p" "$f" >> input.temp;
mv input.temp $filename.temp
done
我在 for 循环中的 sed 命令有问题。我环顾四周,人们建议我添加双引号,但无济于事。我认为这可能是$ p。 我希望这足够清楚。如果不是,我会尝试解释得更好。
sed -n "/0 1/,$p" "$f" >> input.temp; 不起作用
sed -n '/0 1/,$p' "$f" >> input.temp; 不起作用
sed -n "/0 1/,\$p" "$f" >> input.temp; 不起作用
仅供参考,我不想找到其他可行的方法。我想修复这个确切的输入。我敢肯定,我听起来像个混蛋。
示例输入
%sum=8
file=otherpath/filename.txt
some other commands
another description
0 1
0.36920852 -0.56246512
0.77541848 0.05756533
2.05409026 0.62333039
2.92655258 0.56906375
2.52034254 -0.05096652
1.24167014 -0.61673008
-0.60708600 -0.99443872
0.10927459 0.09899803
3.90284624 1.00103940
3.18648588 -0.09239788
0.93151968 -1.09013674
2.50047427 1.30468389
2.19361322 2.54108378
3.18742399 0.34152442
3.38679424 1.11276220
1.56936488 3.27250306
1.81754180 4.19564055
1 2 1.5 6
2 3 1.5
3 4
4 5 1.5
5 6 1.5
6 11 1.0
7
8
9
10
11
12
13 16
14
15
16 17
17
我想要的输出基本上是这个从“0 1”到结尾的文件,前面是我放在 printf 中的东西。
更新:如果您有兴趣,triplee 和 Ed Morton 提供的两个脚本运行良好。我的脚本中的问题是我从 sed 行中省略了 -i 选项(用于就地)。
sed -n "/0 1/,$p" "$f" >> input.temp
应该替换为
sed -ni '/0 1/,$p' "$f"
【问题讨论】:
-
我认为您需要单引号,以防止
$p被视为 shell 变量而不是 sed 代码:sed -n '/0 1/,$p' "$f" >> input.temp。不过,要知道你到底想在那里做什么有点困难。 -
这里的大括号有点古怪。
-
您知道每次连续迭代都会覆盖 inputout.temp2,对吗?我猜这只是一个试验台,但仅供参考
-
我修复了 % 符号问题。 mv 命令应该将临时文件移动到原始文件中以替换它。带简单引号的 sed 不起作用。
-
是的。也许你误解了什么。解决方法是仅在
sed脚本周围使用单引号;sed -n '/0 1/,$p' "$f"所以文件名参数仍应使用双引号。