Linux 使用sed替换从特定行到特定行的整行
我使用以下代码使用sed将特定行替换为特定行:Linux 使用sed替换从特定行到特定行的整行,linux,bash,shell,sed,command-line,Linux,Bash,Shell,Sed,Command Line,我使用以下代码使用sed将特定行替换为特定行: i=5 while (( i <= 10 )) do sed -i '$i s/.*/change/' file.txt ((i++)) done 运行脚本后,file.txt将更改为: 1. alloha 2. this 3. is 4. just 5. a 6. test 7. nonsense 8. words 9. a
i=5
while (( i <= 10 ))
do
sed -i '$i s/.*/change/' file.txt
((i++))
done
运行脚本后,file.txt将更改为:
1. alloha
2. this
3. is
4. just
5. a
6. test
7. nonsense
8. words
9. at
10. all
11. as
12. you
13. can
14. s/.*/change/
15. s/.*/change/
16. s/.*/change/
17. s/.*/change/
18. s/.*/change/
19. s/.*/change/
20. see
我相信sed命令工作得很好,因为我在命令行中测试了它,它可以按照我的要求工作,我认为问题只是来自I
变量
所以有人知道如何使它工作吗?在我搜索了一点之后,我发现如果我想在sed命令中使用变量,我必须使用双引号
“
”
因此,正如您在下面的代码中看到的那样,我将其替换为”
,而不是”
:
i=5
while (( i <= 10 ))
do
sed -i "$i s/.*/change/" file.txt
((i++))
done
i=5
while((i这似乎适用于那个简单的用例,但是sed运行5次只是为了编辑那个文件。sed可以在一次调用中完成,并且在运行sed 5次时不涉及循环
sed -s '5,10s/\(^.*[[:space:]]\)*.*$/\1change/' file.txt
sed -s '5,10s/\(^.*[[:space:]]\)*.*$/\1change/' file.txt