sed command & regular expression error All In One
read data & write data
regexp error
# /regexp/ 正则表达式后面少了一个 `/` ❌
sed "s/div/XYZ" ./multi-line-text.txt
# sed: 1: "s/div/XYZ": unterminated substitute in regular expression
solution
# /regexp/ 正则表达式后面少了一个 `/` ✅
sed "s/div/XYZ/" ./multi-line-text.txt >> multi-line-text.md
<div>line 01</div>
<div>line 02</div>
<div>line 03</div>
<div>line 04</div>
<div>line 05</div>
<div>line 06</div>
<div>line 07</div>
<div>line 08</div>
<div>line 09</div>
<div>line 10</div>
# sed `默认`不会直接修改源文件, 只是返回一个 STDOUT ✅
# sed "s/<div>//" ./multi-line-text.txt
# sed 同时执行多个命令 `-e`, 使用英文的分号分隔 `;` ✅
# sed 的多个命令写在同一个双引号里面
# sed -e "s/<div>//; s/<\/div>//" ./multi-line-text.txt >> multi-line-text.md
sed -e "s/<div>//; s/<\/div>//" ./multi-line-text.txt >> multi-line-text.md
insert data
insert new line data with a line break into first line
# clear first
rm -rf ./multi-line-text.md
# 双引号,多行文本 ❌
# sed -i '' "1i\
# Perl camel\
# " ./multi-line-text.txt
# sed: 1: "1iPerl camel": command i expects \ followed by text
solution 1:
1i
# 单引号,多行文本 ✅ 直接插入数据到原始文件
sed -i '' '1i\
Perl camel\
' ./multi-line-text.txt
# sed -i '' '1i\
# Perl camel\' ./multi-line-text.txt
# sed -i '' "1i\Perl camel" ./multi-line-text.txt
# sed: 1: "1i\Perl camel": extra characters after \ at the end of i command
# sed -i '' "1i Perl camel" ./multi-line-text.txt
# sed: 1: "1i Perl camel": command i expects \ followed by text
solution 2:
1s
# 1s 正则插入, 单引号 ✅
# sed -i '' '1s/^/Perl camel\n/' ./multi-line-text.txt
# 1s 正则插入, 单引号 + 双引号 ✅
# sed -i "" '1s/^/Perl camel\n/' ./multi-line-text.txt
# 1s 正则插入, 双引号 ✅
sed -i "" "1s/^/Perl camel\n/" ./multi-line-text.txt
https://stackoverflow.com/a/74197534/5934465
refs
Linux bash
sed
command All In One
https://www.cnblogs.com/xgqfrms/p/16824934.html
https://www.tutorialspoint.com/how-to-insert-a-text-at-the-beginning-of-a-file-in-linux
https://www.myoungs.com/2019/09/29/sed-of-os-x/
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 ️,侵权必究⚠️!